List Leaves【建立树,层序遍历】

给定一棵树,任务是按照自顶向下、从左到右的顺序列出所有叶子节点的索引。输入包含一棵最多10个节点的树,每个节点的左右子节点索引以空格分隔,不存在的子节点用'-'表示。
摘要由CSDN通过智能技术生成

7-4 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.
在这里插入图片描述

#include<iostream>
#include<queue>
using namespace std;
#define MAX 10

struct Node
{
	int left,right;
}T[MAX];

int buildTree(struct Node T[],int n)
{
	if(n==0) return -1;
	int i,flag[n];
	for(i=0;i<n;i++)
	{
		flag[i]=0;
	}
	
	char cl,cr;
	for(i=0;i<n;i++)
	{
		cin>>cl>>cr;
		
		if(cl!='-')
		{
			T[i].left=cl-'0';
			flag[T[i].left]=1;
		}
		else T[i].left=-1;
		if(cr!='-')
		{
			T[i].right=cr-'0';
			flag[T[i].right]=1;
		}
		else T[i].right=-1;
	}
	for(int i=0;i<n;i++)
		if(flag[i]==0) return i;
}

void findLeaves(int t,queue<int>&Queue,int Leaves[],int* pj)  //层序遍历找叶子 
{
	//cout<<"层序遍历:"; 
	Queue.push(t);
	int node;
	while(Queue.size())
	{
		node=Queue.front();
		Queue.pop();
		if(T[node].left==-1&&T[node].right==-1) Leaves[(*pj)++]=node;
		if(T[node].left!=-1)
			Queue.push(T[node].left);
		if(T[node].right!=-1)
			Queue.push(T[node].right);
	}
}

int main()
{
	int n,i;
	cin>>n;
	int t;
	t=buildTree(T,n);
	//cout<<"root="<<t<<endl;
	
	int Leaves[n],j=0;
	queue<int> Queue;
	for(i=0;i<n;i++) Leaves[i]=0;
	findLeaves(t,Queue,Leaves,&j);
	//cout<<"j="<<j<<endl;
	
	int flag=0;
	for(i=0;i<j;i++)
	{
		if(flag==0) flag=1;
		else cout<<" ";
		cout<<Leaves[i];
	}
	
	return 0;
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值