03-树2 List Leaves(C/C++)

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.
每个输入文件包含一个测试用例。对于每种情况,第一行给出一个正整数N(≤10),这是树中节点的总数,因此节点的编号从0到N - 1。然后是N行,每一行对应一个节点,并给出该节点左右子节点的索引。如果该子元素不存在,则在该位置放置一个“-”。任何一对孩子都用一个空格隔开。

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

思路:

输入样例的第一行意思为,编号0的元素左孩子为1,无右孩子,依此类推。可以得到如下图形:
在这里插入图片描述
按层序遍历可以得到叶子结点(没有左右孩子)为415

代码:
#include<bits/stdc++.h>

using namespace std;

typedef struct node{
	//int data;
	int lchild;
	int rchild;
	bool root=true;
}node;

int main(){
	int n;
	cin>>n;
	node bt[n];
	char l,r;
	int root1;
	int tree[n];
	int isfirst=1;//判断是否为第一个输出 
	for(int i=0;i<n;i++){
		cin>>l>>r;
		if(l=='-'){
			bt[i].lchild=-1;
		}
		else{
			bt[i].lchild=l-'0';
			bt[l-'0'].root=false;//为孩子则不可能为根节点 
		}
		if(r=='-'){
			bt[i].rchild=-1;
		}
		else{
			bt[i].rchild=r-'0';
			bt[r-'0'].root=false;
		}
	}
	//找到根节点 
	for(int i=0;i<n;i++){
		if(bt[i].root==true){
			root1=i;
		}
	}
	
	//层序遍历保存结点的值
	int j=0;
	tree[j++]=root1;
	for(int i=0;i<n;i++){	
		if(bt[tree[i]].lchild!=-1){//有左孩子 
			tree[j++]=bt[tree[i]].lchild;
		}
		if(bt[tree[i]].rchild!=-1){//有右孩子 
			tree[j++]=bt[tree[i]].rchild;
		}
	} 
	
	for(int i=0;i<n;i++){
		if(bt[tree[i]].lchild==-1&&bt[tree[i]].rchild==-1){
			if(isfirst){
				cout<<tree[i];
				isfirst=0;
			} 
			else{
				cout<<" "<<tree[i];
			}
		}
	} 
	return 0;
} 
  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

叶柖

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值