【发布时间】:2015-05-16 12:33:31
【问题描述】:
我在一次采访中被要求打印二叉树的边界。例如。
1
/ \
2 3
/ \ / \
4 5 6 7
/ \ \
8 9 10
答案将是:1、2、4、8、9、10、7、3
我已经给出了以下答案。
第一种方法:
我使用了一个 Bool 变量来解决上述问题。
void printLeftEdges(BinaryTree *p, bool print) {
if (!p) return;
if (print || (!p->left && !p->right))
cout << p->data << " ";
printLeftEdges(p->left, print);
printLeftEdges(p->right, false);
}
void printRightEdges(BinaryTree *p, bool print) {
if (!p) return;
printRightEdges(p->left, false);
printRightEdges(p->right, print);
if (print || (!p->left && !p->right))
cout << p->data << " ";
}
void printOuterEdges(BinaryTree *root) {
if (!root) return;
cout << root->data << " ";
printLeftEdges(root->left, true);
printRightEdges(root->right, true);
}
他的回应:您已经多次使用 Bool 变量。你能在不使用它的情况下解决这个问题吗?
第二种方法:
我只是简单地使用树遍历来解决这个问题。
1. Print the left boundary in top-down manner.
2. Print all leaf nodes from left to right, which can again be sub-divided into two sub-parts:
2.1 Print all leaf nodes of left sub-tree from left to right.
2.2 Print all leaf nodes of right subtree from left to right.
3. Print the right boundary in bottom-up manner.
他的回应:他也对这种方法不满意。他告诉你遍历树 3 次。那太多了。如果您有任何解决方案,请提供其他解决方案。
第三种方法: 这次我选择了Level Order traversal (BFS)。
1: Print starting and ending node of each level
2: For each other node check if its both the children are <b>NULL</b> then print that node too.
他的回应:他似乎对这种方法也不满意,因为这种方法需要额外的 O(n) 阶内存。
我的问题是告诉我一个单次遍历树的方法,不要使用任何 Bool 变量,也不要使用任何额外的内存。有可能吗?
【问题讨论】:
-
我认为 O(1) 次遍历并没有那么糟糕! [第二个解决方案]
-
@Emadpres 这不是 O(1),而是 O(n)。因为我们必须至少遍历所有节点一次。
-
O(1)参考3。穿越 3 次或 1 次并不重要,也许除了雇用
标签: algorithm tree binary-tree binary-search-tree graph-algorithm