print a binary tree in anti-clockwise direction

本文介绍了一种特殊的二叉树遍历方法——逆时针打印完整二叉树的轮廓。具体步骤包括:从根节点开始向下打印左侧边的所有节点;接着按从左到右的顺序打印所有叶子节点;最后再从下至上打印右侧边的所有节点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转自出处

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


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, bool first) {
	if(node == null)
		return;

	print_right(node->rignt, false);
	if (first == false && (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, true);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值