对于给定的二叉树,本题要求你按从上到下、从左到右的顺序输出其所有叶节点。
输入格式:
首先第一行给出一个正整数 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;
typedef struct TreeNode {
struct TreeNode* left;
struct TreeNode* right;
struct TreeNode* parent;
int var;
}TreeNode;
string str;//存放叶子节点下标
//层序遍历寻找叶子结点
void LevelOrder(TreeNode* root) {
int num = 0;//空格判定
int size = str.size();
queue<TreeNode*> q;
if (root) q.push(root);
while (!q.empty()) {
TreeNode* front = q.front();
q.pop();
//如果为叶子节点 则输出
if (str.find(front->var+'0') != -1) {
if (++num != size) {
printf("%d ", front->var);
}
else
printf("%d", front->var);
}
if (front->left) {
q.push(front->left);
}
if (front->right) {
q.push(front->right);
}
}
}
int main()
{
int N;
cin >> N;
getchar();
//构建二叉树
TreeNode* root[N];//N个节点
for (int i = 0; i < N; i++){
root[i] = (TreeNode*)malloc(sizeof(TreeNode));
root[i]->parent = NULL;
}
char ch1, ch2;
for (int i = 0; i < N; i++) {
cin >> ch1 >> ch2;
root[i]->var = i;
if (ch1 == ch2) {
root[i]->left = NULL;
root[i]->right = NULL;
str.push_back(i + '0');
}
else if (ch1 == '-') {
root[i]->left = NULL;
root[i]->right = root[ch2 - '0'];
root[ch2 - '0']->parent = root[i];
}
else if(ch2 == '-'){
root[i]->right = NULL;
root[i]->left = root[ch1 - '0'];
root[ch1 - '0']->parent = root[i];
}
else{
root[i]->left = root[ch1-'0'];
root[i]->right = root[ch2 - '0'];
root[ch1 - '0']->parent = root[i];
root[ch2 - '0']->parent = root[i];
}
}
//找主根
for (int i = 0; i < N; i++)
{
if (root[i]->parent == NULL) {
LevelOrder(root[i]);
break;
}
}
return 0;
}