您的位置:首页 > 其它

根据二叉树的中序和后序遍历,求前序遍历

2017-02-17 22:57 405 查看
先构建二叉树,后进行中序遍历

1.后序的最后一个节点是二叉树的根节点,即前序遍历的第一个节点,找到其在中序遍历中的位置,分为做字数和右子树两部分

                      A

                /           \

           CBH        DE 

2.左子树中的节点在后序遍历中位于最右边的节点是当前根节点,找到其在中序遍历中的位置,以此类推,分别找到左子树和右子树

                    A

                /        \

               B      D

   /  \     \

     C  H   E

所以前序遍历结果是:ABCHDE

#include <iostream>
#include <string>
using namespace std;

typedef struct no
{
char data;
struct no *lchild,*rchild;
}*node;
void create(node &sa,string in,string post)
{
if(in.length()==0)
return;
sa=new no();
sa->data=post[post.length()-1];//根节点
sa->lchild=sa->rchild=NULL;
string inl,inr,postl,postr;
int i=in.find(post[post.length()-1]);
inl=in.substr(0,i);
inr=in.substr(i+1,in.length());
postl=post.substr(0,inl.length());
postr=post.substr(inl.length(),inr.length());
create(sa->lchild,inl,postl);
create(sa->rchild,inr,postr);
}

void pre(node &sa)
{
if(sa!=NULL)
{
cout<<sa->data;
pre(sa->lchild);
pre(sa->rchild);
}
}
int main()
{
string inorder,postorder;
cout<<"请输入中序遍历:"<<endl;
cin>>inorder;
cout<<"请输入后序遍历:"<<endl;
cin>>postorder;
node head=new no();
create(head,inorder,postorder);
cout<<"前序遍历结果:"<<endl;
pre(head);
cout<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: