C 熟悉二叉树的构建 03-树2 List Leaves (25分)

这篇博客介绍了如何使用C语言按照从上到下、从左到右的顺序列出二叉树的所有叶子节点。输入包含节点总数N和每个节点的左右子节点索引,输出是叶子节点的索引序列。解题策略包括构造节点结构体、建立从输入到二叉树的转换函数以及遍历并输出叶子节点的主函数。在输出过程中,通过标记避免最后一个数字后面出现空格。

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

03-树2 List Leaves (25分)

Given a tree, you are supposed to list all the leaves in the order of top down, and left to right.

Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (≤10) which is the total number of nodes in the tree – and hence the nodes are numbered from 0 to N−1. Then N lines follow, each corresponds to a node, and gives the indices of the left and right children of the node. If the child does not exist, a “-” will be put at the position. Any pair of children are separated by a space.

Output Specification:
For each test case, print in one line all the leaves’ indices in the order of top down, and left to right. There must be exactly one space between any adjacent numbers, and no extra space at the end of the line.

Sample Input:

8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6

Sample Output:

4 1 5

简而言之
输入:
节点数 N
N个结点,节点的左子树,右子树索引

输出:
从上到下,从左到右找寻叶节点——左右子树都为空
队列方式——逐个输出 叶的索引,最后不能有空格

解题
1.构造节点类型

struct TreeNode{
	 int left;        //左子树的索引 
	 int right;       //右子树的索引,为空则-1 
	 int value;
}T1[MaxTree]; 

2.创建由输入转为树的函数,树的节点保存在结构数组里
函数返回根节点的坐标。

int notroot[10]={0};
int GetTree(TreeNode T[]){     //返回该数的根节点索引 
	char cl,cr;
	int N;
	int Root;
	scanf("%d\n",&N);           //后面是用是scanf char类型的,所以前面的换行符也要消掉 
	for (int i=0;i<N;i++){
		scanf("%c %c\n",&cl,&cr);   
		//cin>>cl>>cr; 
		if(cl!='-'){
			T[i].left=cl-'0';
			notroot[T[i].left]=1;
		}
		else T[i].left=Null;
		if(cr!='-'){
			T[i].right=cr-'0';
			notroot[T[i].right]=1;
		}
		else T[i].right=Null;
		T[i].value=i;
	}             //所有节点放入数组 
	//找根节点
	for(int i=0;i<N;i++){
		if(!notroot[i]){
			Root=i;
			break;
		}
	} 
	return Root;      //返回根节点坐标 
}

3.主函数
包括输出,
为了不让最后输出空格,则设置标记flag,第一个数前面不输出space,而后面的数都输出space;

int main(){
	int R=GetTree(T1);       //把树存在T1里,并得到根节点索引R
	 //建队列,挨个入队,找到没有左右子树的点,输出
	queue<TreeNode> A;
	A.push(T1[R]);
	queue<int> result;
	int flag =0; 
	while(!A.empty()){
		TreeNode temp = A.front();
		A.pop();
		if(temp.left!=Null){                //从根节点开始 不为空则左右子树入队 
			A.push(T1[temp.left]);    //先左 
		} 
		if(temp.right!=Null){
			A.push(T1[temp.right]);    //后右 
		}
		
		if(temp.right==Null&&temp.left==Null){
			if(flag!=0){
				printf(" ");
			}
			flag=1;
			printf("%d",temp.value);
		}
	}
	return 0;  
}

注意点
二叉树的构建用到结构数组,并先找到根节点,即可遍历二叉树;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值