由中序可以确定多个二叉树,但由中序和前序(或者后序)则可以唯一确定一个二叉树,具体构造方法可以通过递归算法实现:
前序序列:ABHFDECKG
中序序列:HBDFAEKCG
前序字母A将中序划分为两个子序列:((HBDF)A(EKCG)),左子树由(HBDF)构成,右子树由(EKCG)构成
(1)左子树作为一个新的树构建,中序序列为HBDF,前序序列为BHFD
(2)右子树作为一个新的树构建,中序序列为EKCG,前序序列为ECKG
层层划分,最后直到叶子节点,中序为H,则前序也为H,然后再划分H,它的左右子树为空,递归截止,往上回溯!
分解图如下:
具体代码如下:
/*************************************************************************
> File Name: geneteBinaryTree.cpp
> Author: ltf
> Mail: @qq.com
> Created Time: Fri 25 Mar 2016 07:25:07 PM CST
************************************************************************/
#include<iostream>
using namespace std;
typedef struct Tree
{
Tree *left;
Tree *right;
char value;
}*pTree;
// LVR[0,k,n]
// LVR[0] increase always ,yet n is the tail
pTree generateBinaryTree(char *VLR,char *LVR,int n)
{
int k = 0;
if(n == 0)
return NULL;
//if input right k < n
while(VLR[0] != LVR[k]) k++;
Tree *root = new Tree();
root->value = LVR[k];
// [0,n)
root->left = generateBinaryTree(VLR+1,LVR,k);
// new range,[k+1,n-(k+1)) and start of LVR shall be VLR[k+1]
root->right = generateBinaryTree(VLR+k+1,LVR+k+1,n-k-1);
return root;
}
void printPreOrder(Tree *root)
{
if(root != NULL)
{
cout << root->value;
printPreOrder(root->left);
printPreOrder(root->right);
}
}
int main()
{
char VLR[20],LVR[20];
cout << "input the number"<<endl;
int i=0;int n;
cin >> n;
cin.get();
cout << "preOrder number"<< endl;
for(i=0; i<n ;i++)
{
cin.get(VLR[i]);
}
cin.get();
cout << "inOrder number" << endl;
for(i=0; i<n ;i++)
{
cin.get(LVR[i]);
}
Tree *root = generateBinaryTree(VLR ,LVR , n);
cout << "preOrder after generate tree:"<< endl;
printPreOrder(root);
cout << endl;
return 0;
}