前序和中序、中序和后序都可以唯一确定一棵二叉树
前序和后序不可以唯一确定一棵二叉树
#include<iostream>
#include<stdlib.h>
#define maxSize 100
using namespace std;
typedef struct BTNode
{
char data;
struct BTNode *lchild;
struct BTNode *rchild;
}BTNode;
void Visit(BTNode *p)//访问结点
{
cout<<p->data;
}
void preorder(BTNode *p)//先序遍历
{
if(p!=NULL)
{
Visit(p);
preorder(p->lchild);
preorder(p->rchild);
}
}
void inorder(BTNode *p)//中序遍历
{
if(p!=NULL)
{
inorder(p->lchild);
Visit(p);
inorder(p->rchild);
}
}
void postorder(BTNode *p)//后序遍历
{
if(p!=NULL)
{
postorder(p->lchild);
postorder(p->rchild);
Visit(p);
}
}
void CreateBiTree(BTNode *&T,string preorder,string inorder)
{
if(preorder.length()==0)
{
T=NULL;
return ;
}
char r=preorder[0];
//根在中序序列中的位置
int id=inorder.find(r);
//左右孩子的中序序列
string l_inorder=inorder.substr(0,id);
string r_inorder=inorder.substr(id+1);
//左右孩子的长度
int l_length=l_inorder.length();
int r_length=r_inorder.length();
//左右孩子的前序序列
string l_preorder=preorder.substr(1,l_length);
string r_preorder=preorder.substr(1+l_length);
T=(BTNode*)malloc(sizeof(BTNode));
if(T!=NULL)
{
T->data=r;
//递归创建左右孩子
CreateBiTree(T->lchild,l_preorder,l_inorder);
CreateBiTree(T->rchild,r_preorder,r_inorder);
}
}
int main()
{
//前序 和中序 、中序 和后序 都可唯一确定一棵二叉树 ,前和后不可以
string pre="ABCDEFGH";//先序
string in="CBEDFAHG";//中序
BTNode *T;
CreateBiTree(T,pre,in);
cout<<"先序遍历:"; preorder(T); cout<<endl;
cout<<"中序遍历:"; inorder(T); cout<<endl;
cout<<"后续遍历:"; postorder(T); cout<<endl;
}