【发布时间】:2021-09-29 07:36:14
【问题描述】:
在https://www.techiedelight.com/print-all-paths-from-root-to-leaf-nodes-binary-tree/ 中,下面提供了为每个叶节点打印根到叶的代码。
他们说算法是 O(n),但我认为它应该是 O(n log n),其中 n 是节点数。标准 DFS 通常为 O(n + E),但打印路径似乎会添加 log n。假设 h 是完美二叉树的高度。最后一层有 n/2 个节点,因此我们需要打印 n/2 个路径。每条路径都有 h + 1(为了数学简单,我们只是说它是 h)节点。所以我们需要在打印所有路径时最终打印 h * n/2 个节点。我们知道 h = log2(n)。所以 h * n/2 = O(n log n)?
他们的回答是错的,还是我这里的分析有问题?
#include <iostream>
#include <vector>
using namespace std;
// Data structure to store a binary tree node
struct Node
{
int data;
Node *left, *right;
Node(int data)
{
this->data = data;
this->left = this->right = nullptr;
}
};
// Function to check if a given node is a leaf node or not
bool isLeaf(Node* node) {
return (node->left == nullptr && node->right == nullptr);
}
// Recursive function to find paths from the root node to every leaf node
void printRootToleafPaths(Node* node, vector<int> &path)
{
// base case
if (node == nullptr) {
return;
}
// include the current node to the path
path.push_back(node->data);
// if a leaf node is found, print the path
if (isLeaf(node))
{
for (int data: path) {
cout << data << " ";
}
cout << endl;
}
// recur for the left and right subtree
printRootToleafPaths(node->left, path);
printRootToleafPaths(node->right, path);
// backtrack: remove the current node after the left, and right subtree are done
path.pop_back();
}
// The main function to print paths from the root node to every leaf node
void printRootToleafPaths(Node* node)
{
// vector to store root-to-leaf path
vector<int> path;
printRootToleafPaths(node, path);
}
int main()
{
/* Construct the following tree
1
/ \
/ \
2 3
/ \ / \
4 5 6 7
/ \
8 9
*/
Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);
root->right->left = new Node(6);
root->right->right = new Node(7);
root->right->left->left = new Node(8);
root->right->right->right = new Node(9);
// print all root-to-leaf paths
printRootToleafPaths(root);
return 0;
}
【问题讨论】:
标签: c++ algorithm time-complexity