03-树2 List Leaves(c++,一道简单数据结构题)

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();
	}
}
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值