本文最后更新于2363天前,其中的信息可能已经有所发展或是发生改变。
对于给定的二叉树,本题要求你按从上到下、从左到右的顺序输出其所有叶节点。
输入格式:
首先第一行给出一个正整数 N(≤10),为树中结点总数。树中的结点从 0 到 N−1 编号。随后 N 行,每行给出一个对应结点左右孩子的编号。如果某个孩子不存在,则在对应位置给出 "-"。编号间以 1 个空格分隔。
输出格式:
在一行中按规定顺序输出叶节点的编号。编号间以 1 个空格分隔,行首尾不得有多余空格。
输入样例:
8 1 - - - 0 - 2 7 - - - - 5 - 4 6
输出样例:
4 1 5
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <cstdio>
#include <vector>
#include <map>
#include <stack>
#include <string>
#include <queue>
#include <set>
#include <list>
using namespace std;
struct node {
char left, right;
} nd[15];
vector <int> leaf[15];
void fun(int s, int cur) {
if (nd[s].left == '-' && nd[s].right == '-') {
leaf[cur].push_back(s);
return ;
}
if (nd[s].left != '-') fun(nd[s].left - '0', cur + 1);
if (nd[s].right != '-') fun(nd[s].right - '0', cur + 1);
}
int main() {
int n, root[10], rt = 0;
memset(root, 0, sizeof root);
cin >> n;
for (int i = 0; i < n; i++) {
cin >> nd[i].left >> nd[i].right;
root[nd[i].left - '0'] = root[nd[i].right - '0'] = 1;
}
for (int i = 0; i < n; i++)
if (!root[i]) {
rt = i;
break;
}
fun(rt, 1);
bool f = false;
for (int i = 1; i <= 10; i++) {
for (int j = 0; j < leaf[i].size(); j++) {
if (f) cout << " ";
else f = true;
cout << leaf[i][j];
}
}
cout << endl;
}
Hits: 835










