只有已知先序中序求后序 和 已知中序后序求先序两种情况。
如果已知先序后序,是不能确定中序的情况的。
以下是两种情况的代码。
已知先序中序,求后序
#include <iostream>
using namespace std;
struct TreeNode{
int data;
TreeNode* left;
TreeNode* right;
};
void BinaryTreeFromOrderings(int *inorder,int *preorder,int length)//中序序列,先序序列,中序中需要寻找的字段长度
{
if(length==0) return;
TreeNode* node=new TreeNode;//新建一个节点,节点的数据为先序的首个元素
node->data=*preorder;
int rootIndex;//根节点在中序数组中的下标
for(rootIndex=0;rootIndex<length;rootIndex++)
if(inorder[rootIndex]==*preorder) break;
//后序遍历输出结果
BinaryTreeFromOrderings(inorder,preorder+1,rootIndex);//中序的左边一半长度作为新的需要寻找的字段长度
BinaryTreeFromOrderings(inorder+rootIndex+1,preorder+rootIndex+1,length-(rootIndex+1));//中序的后面一段长度作为需要寻找的字段长度
cout<<node->data;
}
已知中序后序,求先序
#include <iostream>
using namespace std;
struct TreeNode{
int data;
TreeNode* left;
TreeNode* right;
};
void BinaryTreeFromOrderings(int *inorder,int *lastorder,int length)//中序序列,先序序列,中序中需要寻找的字段长度
{
if(length==0) return;
TreeNode* node=new TreeNode;
node->data=lastorder+length-1;
int rootindex;
for(rootindex=0;rootindex<length;rootindex++)
if(inorder[rootindex]==node->data)
break;
cout<<node->data<<" ";
BinaryTreeFromOrderings(inorder,lastorder,rootindex);
BinaryTreeFromOrderings(inorder+rootindex+1,lastorder+rootindex,length-(rootindex+1));
}