根据二叉树的中序和后序遍历,求前序遍历
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;
}
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;
}
相关文章推荐
- 根据二叉树的前序遍历序列和中序遍历序列求二叉树的后序遍历序列
- 根据前序遍历和中序遍历构建二叉树以及根据中序遍历后序遍历构建二叉树
- 刷题之路----根据前序遍历和中序遍历或者后序遍历和中序遍历重建二叉树
- 根据前序遍历序列和中序遍历序列构造二叉树
- 根据后序和中序遍历重建二叉树
- POJ 2255Tree Recovery 二叉树重建(根据前序遍历和中序遍历写出后序遍历)
- 如何根据前序遍历和中序遍历重建二叉树
- 根据二叉树的前序遍历和中序遍历的结果,重建二叉树
- 根据二叉树的前序遍历和中序遍历重建二叉树
- 如何根据前序遍历序列和中序遍历序列确定二叉树
- 由二叉树的前序遍历和中序遍历来求后序遍历的结果
- 二叉树根据先序遍历和中序遍历,得到后序遍历
- 剑指offer面试题:输入某二叉树的前序遍历和中序遍历,输出后序遍历
- C++ 根据前序遍历序列和中序遍历序列可以构造唯一的二叉树
- (剑指offer笔记)根据前序遍历和后序遍历重建二叉树
- 阿里笔试-二叉树由前序遍历和中序遍历推导后序遍历
- 根据前序遍历和中序遍历重建二叉树的Java实现
- 二叉树根据前序遍历和中序遍历重构确定唯一二叉树
- 027根据前序遍历和中序遍历,重建二叉树(keep it up)
- poj2255 根据任意二叉树的先序遍历和中序遍历求解后序遍历