[Google] print the outline of a complete binary tree in anti-clockwise direction

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: 

/ \ 
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);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值