列出叶结点
对于给定的二叉树,本题要求你按从上到下、从左到右的顺序输出其所有叶节点。
输入格式:
首先第一行给出一个正整数 N(≤10),为树中结点总数。树中的结点从 0 到 N−1 编号。随后 N 行,每行给出一个对应结点左右孩子的编号。如果某个孩子不存在,则在对应位置给出 "-"。编号间以 1 个空格分隔。
输出格式:
在一行中按规定顺序输出叶节点的编号。编号间以 1 个空格分隔,行首尾不得有多余空格。
输入样例:
8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6
输出样例:
4 1 5
先找出根结点,然后再层次遍历找叶子即可,AC代码如下:
#include<iostream>
#include<string.h>
#define MAX 15
using namespace std;
typedef struct BiTNode
{
int lchild;
int rchild;
}BiTNode;
BiTNode p[MAX];
int n,root,arr[MAX];
int build()
{
char a,b;
cin >> n;
getchar();
for(int i = 0;i < n; i++)
{
cin >> a >> b;
if(a != '-')
{
p[i].lchild = a - '0';
arr[p[i].lchild]++;
}
else
p[i].lchild = -1;
if(b != '-')
{
p[i].rchild = b - '0';
arr[p[i].rchild]++;
}
else
p[i].rchild = -1;
}
for(int i = 0;i < n; i++)
if(!arr[i])
return i;
}
void level()
{
int fx,head = 0,tail = 0,flag = 0,que[MAX];
memset(que,0,sizeof(que));
que[tail++] = root;
while(head < tail)
{
fx = que[head];
if(p[fx].lchild == -1 && p[fx].rchild == -1)
{
!flag ? cout << fx : cout <<" "<< fx;
flag++;
}
else if(p[fx].lchild != -1 && p[fx].rchild != -1)
{
que[tail++] = p[fx].lchild;
que[tail++] = p[fx].rchild;
}
else if(p[fx].lchild == -1)
que[tail++] = p[fx].rchild;
else
que[tail++] = p[fx].lchild;
head++;
}
}
int main()
{
root = build();
level();
return 0;
}