您的位置:首页 > 其它

旧话重提,根据先序和中序遍历构造二叉树并后序遍历验证之

2009-10-10 22:52 357 查看
详细见注释乐,放码子:

#include"stdafx.h"
#include<iostream>
#include<stack>
using namespace std;
typedef struct tr
{
int data;
tr *left,*right;
}tre,*tree;//先序是根左右,中序是左根右
stack<tree>st;
tree re_creat(int *pre,int *mid,int n)//n是元素个数
{
tree root;
int *rot,k;
if(n<=0)
return NULL;
root=new tre;
root->data=*pre;//记录下先序遍历的第一个数,根
for(rot=mid;rot<mid+n;rot++)//拿着根到中序遍历序列中去划分地盘
if(*rot==*pre)
break;
k=rot-mid;//k跳到根所在的位置,表明为界限
root->left=re_creat(pre+1,mid,k);//分别在各自的地盘递归构造左子树和右子树,分封诸侯国
root->right=re_creat(pre+1+k,rot+1,n-1-k);//根节点的右子树
return root;
}
void lrb(tree root)
{
tree tmp;
while(NULL!=root || !st.empty())
{
if(NULL!=root)
{
st.push(root);
root=root->left;
}
else
{
root=st.top();
if(root->right!=NULL && tmp!=root->right)
root=root->right;
else
{
root=tmp=st.top();
printf("%d ",root->data);
st.pop();
root=NULL;
}
}
}
}
int main()
{
int pre[100],mid[100],n,i;
tree tmp;
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&pre[i]);
for(i=0;i<n;i++)
scanf("%d",&mid[i]);
tmp=re_creat(pre,mid,n);
lrb(tmp);//后序遍历,确认结果正确
return false;
}


附测试数据:

in:

11
7 1 0 2 3 4 68 22 32 93 87
0 1 2 3 4 7 22 32 68 87 93

out:

0 4 3 2 1 32 22 87 93 68 7
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐