我在面试中被要求打印二叉树的边界。例如:
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次。那太多了。如果你有其他解决方案,请给出。
第三种方法: 这次我采用了层序遍历(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)空间。
我的问题是:告诉我一种只遍历树一次、不使用任何布尔变量和额外内存的方法。这是否可能?
O(1)
指的是3
。遍历 3 次或 1 次并不重要,除非需要使用。 - Emadpres