对于给定的二叉树,本题要求你按从上到下、从左到右的顺序输出其所有叶节点。
输入格式:
首先第一行给出一个正整数 N(≤10),为树中结点总数。树中的结点从 0 到 N−1 编号。随后 N 行,每行给出一个对应结点左右孩子的编号。如果某个孩子不存在,则在对应位置给出 "-"。编号间以 1 个空格分隔。
输出格式:
在一行中按规定顺序输出叶节点的编号。编号间以 1 个空格分隔,行首尾不得有多余空格。
输入样例:
8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6
输出样例:
4 1 5
叶节点即没有孩子的节点。考虑到需要从上到下从左到右输出,可以用bfs层序遍历。
用l,r哈希记录左右孩子,p记录父亲节点。
#include<iostream>
#include<cctype>
#include<unordered_map>
#include<cstring>
#include<queue>
#include<vector>
using namespace std;
const int N = 15;
int d[N], p[N];
int n;
unordered_map<int, int> l, r;
vector<int> res;
void bfs(int root){
queue<int> q;
q.push(root);
while(q.size()){
auto t = q.front(); //cout << r[3] << endl;
q.pop();
if(l[t] == -1 && r[t] == -1) res.push_back(t); //记录叶节点
if(l[t] != -1) q.push(l[t]);
if(r[t] != -1) q.push(r[t]);
}
}
int main() {
cin >> n;
memset(p, -1, sizeof p); //父节点初始化为-1
for(int i = 0; i < n; ++ i) {
char a, b;
cin >> a >> b;
if(isdigit(a)) { //记录父节点和左右孩子
p[a-'0'] = i;
l[i] = a-'0';
}else l[i] = -1;
if(isdigit(b)) {
p[b-'0'] = i;
r[i] = b-'0';
}else r[i] = -1;
}
int i = 0;
while(p[i] != -1) i = p[i]; //找到根节点
bfs(i); //层序遍历
cout << res[0];
for(int i = 1; i < res.size(); ++ i) cout << ' ' << res[i];
return 0;
}