Question:
Given a complete binary tree, print the outline of the tree in anti-clockwise direction, starting from the root. I.e. first print all the nodes on the left
edge of the tree going downwards, then print all the leaves going left to right (including leaves on both the last and the 2nd last level if necessary), then
print the nodes on the right edge of the tree going upwards.
Example tree:
A
/ \
B C
/ \ / \
D E F G
/ \ /
H I J
Expected Output: ABDHIJFGC
Solution:
1.这题表明是个完全二叉树,我们可以考虑额外用一个数组保存树(充分利用题目中给定的条件).假定数组大小为n,
1)遍历所有左边节点.则是 1 ,2 ,4,8,....,k(k<=n).
2)遍历所有叶子节点,遍历叶子节点分两部分,第一部分从k后面开始直到n,接着是从n/2+1到k-1.
3)访问右边节点,n/2,n/4,n/8,...,直到1(当然不包括1)
2.如果该题不说是完全二叉树,那我们如何基于树本身来访问呢?道理也是如上述,
1)向下访问左边节点.
2)访问所有叶子节点.
3)向上访问右边节点
void print_left(Node *node) {
if(node == null)
return;
if (node -> left != NULL || node->right != NULL)
printf("%d ", node->v);
print_left(node->left);
}
void print_right(Node *node) {
if(node == null)
return;
print_right(node->rignt);
if (node -> left != NULL || node->right != NULL)
printf("%d ", node->v);
}
void print_leafs(Node *node) {
if (node == NULL)
return;
if (node->left == NULL && node->right == NULL) {
printf("%d ", node->v);
}
print_leafs(node->left);
print_leafs(node->right);
}
void print_outline(Node *root) {
print_left(root);
print_leafs(root);
print_right(root);
}