03-树2 List Leaves(c++,一道简单数据结构题)
给定一棵树,您应按从上到下、从左到右的顺序列出所有叶子节点。
输入规格:每个输入文件包含一个测试用例。对于每个案例,第一行给出一个正整数N(≤10),这是树中总节点的数量,因此节点编号从0到N−1。接着是N行,每行对应一个节点,给出该节点的左右孩子的索引。如果孩子不存在,则在该位置放置一个"-"。任何一对孩子之间都由一个空格分隔。
输出规格:对于每个测试用例,在一行中打印出所有叶子节点的索引,按照从上到下、从左到右的顺序。任何相邻数字之间必须正好有一个空格,行末没有额外的空格。
本题思路
首先,根据有索引顺序的节点建立一棵树,我们先找到根节点,就是那个没出现的节点;
之后,就是层序遍历(dfs)很简单输出就行
Sample Input:
8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6
Sample Output:
4 1 5
#include <bits/stdc++.h>
using namespace std;
#define iloves ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define int long long
const int MAX_N = 3e5 + 10;
struct TreeNode{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x):val(x),left(nullptr),right(nullptr){}
};
int flag[12];
map<int,pair<int,int > >mp;
int n,a_num,b_num,temp;
string a,b;
vector<int>vc;
TreeNode* build(int num){
TreeNode* root =new TreeNode(num);
if(mp[num].first!=-1)root->left=build(mp[num].first);
if(mp[num].second!=-1)root->right=build(mp[num].second);
return root;
}
vector<int>levelOrder(TreeNode* root){
queue<TreeNode*>que;
vector<int>vec;
que.push(root);
while(!que.empty()){
TreeNode *p=que.front();
que.pop();
if(p->left==nullptr&&p->right==nullptr)vec.push_back(p->val);
else {
if(p->left!=nullptr)que.push(p->left);
if(p->right!=nullptr)que.push(p->right);
}
}
return vec;
}
void slove() {
cin>>n;
for(int i=0;i<n;i++){
cin>>a>>b;
if(a!="-"){a_num=stoll(a);flag[a_num]=1;}
else a_num=-1;
if(b!="-"){b_num=stoll(b);flag[b_num]=1;}
else b_num=-1;
mp[i]=make_pair(a_num,b_num);
}
for(int i=0;i<n;i++){
if(flag[i]==0){temp=i;break;}
}
TreeNode *cnt_root = new TreeNode(temp);
cnt_root=build(temp);
vc=levelOrder(cnt_root);
int lengh=vc.size();
if(lengh!=0)cout<<vc[0];
for(int i=1;i<lengh;i++){
cout<<" "<<vc[i];
}
cout<<endl;
}
signed main() {
iloves;
int test = 1;
while (test--) {
slove();
}
}