二叉树的遍历

完全二叉树的性质
  1. i>1的节点,其父节点为i/2
  2. 如果2i>k,那么i没有孩子;如果2i+1>k,那么i没有孩子
  3. 如果节点i有孩子,那么它的左孩子是2i,右孩子是2i+1
二叉树的三种遍历方法
  1. 先序遍历:按父节点、左儿子、右儿子的顺序进行访问。
  2. 中序遍历:按左儿子、父节点、右儿子的顺序进行访问。
  3. 后序遍历:按左儿子、右儿子、父节点的顺序进行访问。

中序遍历+先序遍历 或者 中序遍历+后序遍历 都能确定一棵树。
但只有 先序遍历+后续遍历 不能确定一棵树。

例题 (hdu1710

输入二叉树的的先序遍历和中序遍历,求后序遍历。
输入样例
9
先序:1 2 4 7 3 5 8 9 6
中序:4 7 2 1 8 5 9 3 6
输出样例
后序:7 4 2 8 9 5 6 3 1

题目分析

先序遍历的第一个数是整棵树的根节点(如样例中的 1)。知道了根节点,对照中序遍历,根节点左边的点都在根节点的左子树上(如样例中的 4 7 2),右边的点都在根节点的右子树上(如样例中的 8 5 9 3 6)。

代码如下
#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <map>
#include <queue>
#include <vector>
#include <set>
#include <algorithm>
#include <iomanip>
#define LL long long
#define PII pair<int,int>
using namespace std;
const int N=1e3+5,INF=0x3f3f3f3f;
struct Node{
	int val;
	Node *l,*r;
	Node(int val=0,Node *l=NULL,Node *r=NULL)
		:val(val),l(l),r(r)
	{}
};
int cnt;
int in[N],pre[N],post[N];		//存储中序遍历、先序遍历、后序遍历
void build(int l,int r,int &t,Node* &root)	//建树
{
	int k=-1;
	for(int i=l;i<=r;i++)
		if(in[i]==pre[t])
		{
			k=i;
			break;
		}
	
	if(k==-1) return;
	t++;
	root=new Node(in[k]);
	if(k>l) build(l,k-1,t,root->l);
	if(k<r) build(k+1,r,t,root->r);
}
void preorder(Node *root)		//求二叉树的先序遍历(对这个题来说没用)
{
	if(root!=NULL)
	{
		pre[++cnt]=root->val;
		preorder(root->l);
		preorder(root->r);
	}
}
void inorder(Node *root)		//求二叉树的中序遍历(对这个题来说没用)
{
	if(root!=NULL)
	{
		inorder(root->l);
		in[++cnt]=root->val;
		inorder(root->r);
	}
}
void postorder(Node *root)		//求二叉树的先序遍历
{
	if(root!=NULL)
	{
		postorder(root->l);
		postorder(root->r);
		post[++cnt]=root->val;
	}
}
void remove(Node *root)			//删除二叉树(释放内存)
{
	if(root==NULL) return;
	remove(root->l);
	remove(root->r);
	delete root;
}
int main()
{
	int n;
	while(~scanf("%d",&n))
	{
		for(int i=1;i<=n;i++) scanf("%d",&pre[i]);
		for(int i=1;i<=n;i++) scanf("%d",&in[i]);
		Node *root;
		int t=1;
		build(1,n,t,root);
		
		cnt=0;
		postorder(root);
		for(int i=1;i<cnt;i++)
			printf("%d ",post[i]);
		printf("%d\n",post[cnt]);
		remove(root);
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

lwz_159

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

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

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

打赏作者

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

抵扣说明:

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

余额充值