完全二叉树的性质
- i>1的节点,其父节点为i/2
- 如果2i>k,那么i没有孩子;如果2i+1>k,那么i没有孩子
- 如果节点i有孩子,那么它的左孩子是2i,右孩子是2i+1
二叉树的三种遍历方法
- 先序遍历:按父节点、左儿子、右儿子的顺序进行访问。
- 中序遍历:按左儿子、父节点、右儿子的顺序进行访问。
- 后序遍历:按左儿子、右儿子、父节点的顺序进行访问。
中序遍历+先序遍历
或者 中序遍历+后序遍历
都能确定一棵树。
但只有 先序遍历+后续遍历 不能确定一棵树。
例题 (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;
}