对于给定的二叉树,本题要求你按从上到下、从左到右的顺序输出其所有叶节点。
输入格式:
首先第一行给出一个正整数 N(≤10),为树中结点总数。树中的结点从 0 到 N−1 编号。随后 N 行,每行给出一个对应结点左右孩子的编号。如果某个孩子不存在,则在对应位置给出 “-”。编号间以 1 个空格分隔。
输出格式:
在一行中按规定顺序输出叶节点的编号。编号间以 1 个空格分隔,行首尾不得有多余空格。
输入样例:
8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6
输出样例:
4 1 5
直接代码:
#include<iostream>
#include<stdio.h>
#include<queue>
using namespace std;
struct node
{
int left,right;
};
node T1[10];
int creat(node *t)
{
int n;
cin>>n;
int check[n];
for(int i(0);i<n;i++)
{
check[i]=0;
}
for(int i(0);i<n;i++)
{
char l,r;
cin>>l>>r;
if(l=='-')
{
t[i].left=-1;
}
else
{
t[i].left=l-'0';
check[t[i].left]=1;
}
if(r=='-')
{
t[i].right=-1;
}
else
{
t[i].right=r-'0';
check[t[i].right]=1;
}
}
for(int i(0);i<n;i++)
{
if(check[i]==0)
{
return i;
}
}
return -1;
}
int flag=0;
void cengxubianli(int r,node *t)
{
int in=0;
int out=0;
int a[100];
a[in++]=r;
while (in>out)
{
if(a[out]!=-1)
{
if(t[a[out]].left==-1&&t[a[out]].right==-1)
{
if(flag==0)
{
cout<<a[out];
flag=1;
}
else if(flag==1)
{
cout<<" "<<a[out];
}
}
a[in++]=t[a[out]].left;
a[in++]=t[a[out]].right;
}
out++;
}
}
int main()
{
int root;
root=creat(T1);
cout<<root<<endl;
cengxubianli(root, T1);
}
Work Hard, Stay Humble!
版权声明:本文为kleinzhen原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。