对于给定的二叉树,本题要求你按从上到下、从左到右的顺序输出其所有叶节点。
输入格式:
首先第一行给出一个正整数 N(≤10),为树中结点总数。树中的结点从 0 到 N−1 编号。随后 N 行,每行给出一个对应结点左右孩子的编号。如果某个孩子不存在,则在对应位置给出 "-"。编号间以 1 个空格分隔。
输出格式:
在一行中按规定顺序输出叶节点的编号。编号间以 1 个空格分隔,行首尾不得有多余空格。
输入样例:
8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6
输出样例:
4 1 5
#include <bits/stdc++.h>
using namespace std;
struct node
{
int left;
int right;
}p[50];
int to_gett_char(char ch){
if(ch == '-')
return -1;
return ch - '0';
}
int to_get_root(){
int n;
cin>>n;
int *root = (int *)malloc(n * sizeof(int));
for(int i = 0; i < n; i++)
root[i] = 0;
for (int i = 0; i < n; ++i)
{
char a, b;
cin>>a>>b;
p[i].left = to_gett_char(a);
p[i].right = to_gett_char(b);
root[p[i].left] = 1;
root[p[i].right] = 1;
}
for(int i = 0; i < n; i++)
if(!root[i])
return i;
return -1;
}
void solve(){
int root = to_get_root();
queue<int> q;
q.push(root);
bool is_fitst = true;
while(!q.empty()){
int root = q.front();
q.pop();
if(p[root].left == -1 && p[root].right == -1){
if(is_fitst) printf("%d", root), is_fitst = false;
else printf(" %d", root);
}
if(p[root].left != -1) q.push(p[root].left);
if(p[root].right != -1) q.push(p[root].right);
}
}
int main(int argc, char const *argv[])
{
solve();
return 0;
}