二叉树的先序遍历

题目描述

现有一棵n个结点的二叉树(结点编号为从0n-1,根结点为0号结点),求这棵二叉树的先序遍历序列。

输入描述

第一行一个整数n(1≤n≤50​​​​),表示二叉树的结点个数;

接下来n行,每行一个结点,按顺序给出编号从0n-1的结点的左子结点编号和右子结点编号,中间用空格隔开。如果不存在对应的子结点,那么用-1表示。

输出描述

输出n个整数,表示先序遍历序列,中间用空格隔开,行末不允许有多余的空格。

输入样例

6 2 5 -1 -1 1 4 -1 -1 -1 -1 -1 3

输出样例

0 2 1 4 5 3

代码:

#include<bits/stdc++.h>
using namespace std;
struct Node{
	int l,r;
}node[1005];
vector<int> pre;
void preorder(int root){
	if(root==-1){
		return;
	}
	pre.push_back(root);
	preorder(node[root].l);
	preorder(node[root].r);	
}
int main(){
	int n;
	cin>>n;
	for(int i = 0;i<n;i++){
		cin>>node[i].l>>node[i].r;	
	}
	preorder(0);
	for(int i = 0;i<pre.size();i++){
		cout<<pre[i];
		if(i!=pre.size()-1){
			cout<<" ";
		}
	}
}

相关推荐

  1. 2024-03-12 03:14:02       24 阅读
  2. ,中,后

    2024-03-12 03:14:02       41 阅读
  3. 便利,中,后

    2024-03-12 03:14:02       9 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-03-12 03:14:02       19 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-03-12 03:14:02       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-03-12 03:14:02       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-03-12 03:14:02       20 阅读

热门阅读

  1. LeetCode每日一题[c++]-找出字符串的可整除数组

    2024-03-12 03:14:02       21 阅读
  2. linux系统简述docker

    2024-03-12 03:14:02       19 阅读
  3. 优雅应对商业谈判中的软件质疑

    2024-03-12 03:14:02       24 阅读
  4. Nest.js总结

    2024-03-12 03:14:02       20 阅读
  5. explicit关键字详解

    2024-03-12 03:14:02       18 阅读
  6. ms office学习记录10:Excel㈣

    2024-03-12 03:14:02       17 阅读
  7. LeetCode 560 和为K的子数组

    2024-03-12 03:14:02       22 阅读
  8. LeetCode904:水果成篮

    2024-03-12 03:14:02       16 阅读
  9. 【Leetcode】top 100 子串

    2024-03-12 03:14:02       24 阅读
  10. [力扣 Hot100]Day50 二叉树中的最大路径和

    2024-03-12 03:14:02       21 阅读
  11. LaTex 笔记

    2024-03-12 03:14:02       23 阅读
  12. Docker部署的MySQL容器数据备份与导入

    2024-03-12 03:14:02       25 阅读
  13. skynet cluster集群笔记

    2024-03-12 03:14:02       18 阅读
  14. 无人机避障技术

    2024-03-12 03:14:02       21 阅读