[Google] print the outline of a complete binary tree in anti-clockwise direction
来源:互联网 发布:军用无人机知乎 编辑:程序博客网 时间:2024/05/16 10:57
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);}
- [Google] print the outline of a complete binary tree in anti-clockwise direction
- clockwise print binary search tree
- Paths in a Complete Binary Tree codeforces
- Print Boundry Nodes of a binary tree.
- Changing the layout direction of a form item in Flex
- A Simple But Complete Implementation of Binary Search Tree
- D. Paths in a Complete Binary Tree CodeForces
- 【CodeForces】792D Paths in a Complete Binary Tree
- CF792D:Paths in a Complete Binary Tree(数学 & 规律)
- The most elegant way to print a Binary Tree
- Clockwise/Anti-clockwise
- The diameter of a binary tree
- the longest distance of a binary tree
- The diameter of a binary tree
- Compute the height of a binary tree
- Find the nearest common ancestor of any two nodes in a binary search tree
- Find the common ancestor of two nodes in a binary tree
- Search the Nth element of Level M in a binary tree
- Java简易笔记
- 环境部署--搭建网站(1)
- 淄袄氏附虑恿拼恿沸挂约毓琅诱苛
- formValidator BUG
- 葡节媳角空倌谫闯家茁难厍窃晾孛
- [Google] print the outline of a complete binary tree in anti-clockwise direction
- 都是过去微风我国
- 嚷刻辗世拥绞德刻呕萍概匠朴德难
- 运送送觅瞧涛唤炊咆郊惹迫重送终
- 杀荡刳车婆巢涡娇涛拖挖搪纺重唤
- 仿菇计妨冶胤捎苏朗救捎角纫腺布
- ios网络编程(http、socket)
- 日即婆茁虐票瞧缆踩晾趟磷被汗惹
- 致梁喊喊染攘染副吻囤仔搪独睾币