二叉树后序: 左 - > 右 - > 根 后序给出的最后一个节点为根节点
二叉树中序: 左 - > 根 - > 右 中序可以在前序的基础上将树的左孩子,右孩子,完全确定。 下面就是一个递归的过程
每次递归过程中 拿当前传入的后序遍历的尾节点 找到中序遍历的该尾节点的位置。并将其划分为左右两个子树。并链接在结构体指针上
#include <iostream>
#include <string.h>#include <string>
#include <stdlib.h>
#include <stdio.h>
#include <queue>
using namespace std;
typedef struct Treenode * BinTree;
struct Treenode
{
int Data;
BinTree Left;
BinTree Right;
};
BinTree CreatTreeBin(int In[], int Back[],int len)
{
BinTree T;
if(len==0)
return NULL;
T=(struct Treenode *)malloc(sizeof(struct Treenode));
T->Data=Back[len-1];
int i;
for(i=0;i<len;i++)
{
if(In[i]==Back[len-1]) //在中序遍历中,找到后序遍历尾节点位置
{
break;
}
}
T->Right=CreatTreeBin(In+i+1,Back+i,len-i-1); //在中序遍历中找到根节点位置后,其右侧即为右子树
T->Left=CreatTreeBin(In,Back,i); //在中序遍历中找到根节点位置后,其左侧即为左子树
//传参时注意,后序遍历的尾节点已使用,调整传参长度,不使其传入
return T;}
int Height(BinTree T) //查询树高
{
int Theigth,Lheight,Rheight;
if(!T)
Theigth =0;
else
{
Lheight=Height(T->Left);
Rheight=Height(T->Right);
Theigth=(Lheight>Rheight)?Lheight:Rheight;
Theigth++;
}
return Theigth;
}
void build(BinTree BT) //层序遍历
{
BinTree T;
queue <BinTree> q;
if(!BT)
return ;
q.push(BT);
int flag=0;
while(q.size())
{
T=q.front();
q.pop();
if(flag==1)
printf(" ");
if(flag==0)
flag=1;
printf("%d",T->Data);
if(T->Left)
{
q.push(T->Left);
}
if(T->Right)
{
q.push(T->Right);
}
}
`
}
int main()
{
int In[100],Back[100];
int N;
BinTree T=NULL;
cin>>N;
int i;
for(i=0;i<N;i++)
{
cin>>Back[i];
}
for(i=0;i<N;i++)
{
cin>>In[i];
}
T=CreatTreeBin(In,Back,N);
build(T);
return 0;
}
/*
9
dbefaghci
defbhgica
*/