二叉树的前、中、后序排列

前序排列

前序排列就是按照根、左子树、右子树的顺序输出。

搜索顺序如下:

void pro_dfs(int rt)//rt为当前节点
{
	if(rt == -1) return; //当该点不存在时返回上一个点
	cout << ' ' << tree[rt].u;//输出当前节点
	pro_dfs(tree[rt].lc);//扩展到左子树
	pro_dfs(tree[rt].rc);//扩展到右子树
}



中序排列

中序排列即为按照左子树、根、右子树的顺序输出。

搜索顺序如下:

void mid_dfs(int rt)
{
	if(rt == -1) return;
	mid_dfs(tree[rt].lc);
	cout << ' ' << tree[rt].u;
	mid_dfs(tree[rt].rc);
}



后序排列

按照左子树、右子树、根的顺序输出。

搜索顺序如下:

void post_dfs(int rt)
{
	if(rt == -1) return;
	post_dfs(tree[rt].lc);
	post_dfs(tree[rt].rc);
	cout << ' ' << tree[rt].u;
}



代码

#include <bits/stdc++.h>

using namespace std;

const int maxn = 100010;
int n;

struct hzw
{
	int lc,rc,u,fa;//左子树,右子树,当前节点,父亲节点
}tree[maxn];

void pro_dfs(int rt)//前序排列
{
	if(rt == -1) return;
	cout << ' ' << tree[rt].u;
	pro_dfs(tree[rt].lc);
	pro_dfs(tree[rt].rc);
}

void mid_dfs(int rt)//中序排列
{
	if(rt == -1) return;
	mid_dfs(tree[rt].lc);
	cout << ' ' << tree[rt].u;
	mid_dfs(tree[rt].rc);
}

void post_dfs(int rt)//后序排列
{
	if(rt == -1) return;
	post_dfs(tree[rt].lc);
	post_dfs(tree[rt].rc);
	cout << ' ' << tree[rt].u;
}

int main()
{
	cin >> n;
	for(int i=0; i<maxn; i++)//初始化
	{
		tree[i].lc = -1;
		tree[i].rc = -1;
		tree[i].u = -1;
		tree[i].fa = -1;
	}
	for(int i=0; i<n; i++)//建树
	{
		int rt,lc,rc;
		cin >> rt >> lc >> rc;
		tree[rt].u = rt;
		tree[rt].lc = lc;
		tree[rt].rc = rc;
		if(lc != -1) tree[lc].fa = rt;
		if(rc != -1) tree[rc].fa = rt;
	}
	int root;
	for(int i=0; i<n; i++)//找到根节点
	{
		if(tree[i].fa == -1)
		{
			root = i;
			break;
		}
	}
	
	cout << "Preorder\n";
	pro_dfs(root);
	cout << endl;
	cout << "Inorder\n";
	mid_dfs(root);
	cout << endl;
	cout << "Postorder\n";
	post_dfs(root);
	return 0;
} 
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值