B3642 二叉树的遍历

题目描述

有一个 n(n \le 10^6)n(n≤106) 个结点的二叉树。给出每个结点的两个子结点编号(均不超过 nn),建立一棵二叉树(根节点的编号为 11),如果是叶子结点,则输入 0 0

建好树这棵二叉树之后,依次求出它的前序、中序、后序列遍历。

输入格式

第一行一个整数 nn,表示结点数。

之后 nn 行,第 ii 行两个整数 ll、rr,分别表示结点 ii 的左右子结点编号。若 l=0l=0 则表示无左子结点,r=0r=0 同理。

输出格式

输出三行,每行 nn 个数字,用空格隔开。

第一行是这个二叉树的前序遍历。

第二行是这个二叉树的中序遍历。

第三行是这个二叉树的后序遍历。

输入输出样例

输入 #1

7
2 7
4 0
0 0
0 3
0 0
0 5
6 0

输出 #1

1 2 4 3 7 6 5
4 3 2 1 6 5 7
3 4 2 5 6 7 1 

如下代码使用的是递归的方法实现二叉树的遍历,

#include<iostream>
#include <vector>
#include <algorithm>
using namespace std; 
struct node{
	int root;
	int lchild;
	int rchild;
}node1[1000006];//定义结构体,创建二叉树

//运用递归的方法找出遍历结果
void preorder(int root)//先序遍历,根左右
{	
	if(node1[root].root!=0)
	{
		cout<<node1[root].root<<" ";
	}
	if(node1[root].lchild==0&&node1[root].rchild==0)//直到找到叶子结点
	{
		return ;
	} 
	preorder(node1[root].lchild);
	preorder(node1[root].rchild);
}
void midorder(int root)//中序遍历,左根右
{	
	if(node1[root].lchild!=0)//找到二叉树中最左边的结点
	{
		midorder(node1[root].lchild);
	}

	if(node1[root].root!=0)
	{
		cout<<node1[root].root<<" ";
	}
	if(node1[root].rchild==0)//右结点为叶子结点的时候停止
	{
		return ;
	} 
	midorder(node1[root].rchild);
}
void lastorder(int root)//后序遍历,左右根
{	
	if(node1[root].lchild!=0)//找到二叉树中最左边的结点
	{
		lastorder(node1[root].lchild);
	}
	if(node1[root].rchild!=0)//找到二叉树中最右边的结点
	{
		lastorder(node1[root].rchild);
	}
	if(node1[root].root!=0)
	{
		cout<<node1[root].root<<" ";
	}
}
int main()
{
	int n;
	cin>>n;
	int x,y;
	for(int i=1;i<=n;i++)
	{
		cin>>x>>y;
		node1[i].root=i;
		node1[i].lchild=x;
		node1[i].rchild=y;
	}  //根据题意在二叉树中存入数据
	preorder(1);//调用先序遍历
	cout<<"\n";
	midorder(1);//调用中序遍历
	cout<<"\n";
	lastorder(1);//调用后序遍历
	return 0;
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ssssss555555777777

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值