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个节点的树,每个节点的左右子节点索引以空格分隔,不存在的子节点用'-'表示。
7252

被折叠的 条评论
为什么被折叠?



