根据前序跟中序 => 后序
#include
#include
#include
using namespace std;
struct BTreeNode
{
int _value;
BTreeNode*_left;
BTreeNode*_right;
};
//解法一
BTreeNode* RebuildCode(int * PreStart, int *PreEnd, int *InStart, int *InEnd)
{
BTreeNode *root = new BTreeNode();
//新建节点root保存前序第一个节点为根结点
root->_value = PreStart[0];
root-> _left = NULL;
root->_right = NULL;
if(InStart == InEnd && *InStart == *InEnd)
{
return root;
}
//据此节点找到中序遍历此节点的位置
int *rootIn = InStart;
while(*PreStart != *rootIn)
{
rootIn++;
}
//左子树的长度
int leftlen = rootIn-InStart;
//重建左子树
if(leftlen > 0)
{
root->_left = RebuildCode( PreStart+1, PreStart+leftlen, InStart,InStart+leftlen-1);
}
//重建右子树
if(InStart+leftlen < InEnd)
{
root->_right = RebuildCode( PreStart+leftlen+1, PreEnd,InStart+leftlen+1, InEnd);
}
return root;
}
BTreeNode* RebuildTree(int *PreOrder, int *InOrder, int len)
{
//首先判断边界条件
if(PreOrder == NULL || InOrder == NULL || len <= 0)
{
return NULL;
}
else
{
return RebuildCode(PreOrder, PreOrder+len-1, InOrder, InOrder+len-1);
}
}
//后序遍历输出二叉树序列
void PostOrder(BTreeNode *root)
{
if(root->_left != NULL)
{
PostOrder(root->_left);
}
if(root->_right != NULL)
{
PostOrder(root->_right);
}
if(root != NULL)
{
cout<_value<<" ";
}
}
int main()
{
int PreOrder[8] = {1,2,4,7,3,5,6,8};
int InOrder[8] = {4,7,2,1,5,3,8,6};
PostOrder(RebuildTree(PreOrder, InOrder, 8));
cout<
#include
#include
#include
using namespace std;
struct BTreeNode
{
int _value;
BTreeNode*_left;
BTreeNode*_right;
};
//解法一
BTreeNode* RebuildCode(int * PostStart, int *PostEnd, int *InStart, int *InEnd)
{
BTreeNode *root = new BTreeNode();
//新建节点root保存前序第一个节点为根结点
root->_value = PostEnd[0];
root-> _left = NULL;
root->_right = NULL;
if(InStart == InEnd && *InStart == *InEnd)
{
return root;
}
//据此节点找到中序遍历此节点的位置
int *rootIn = InStart;
while(*PostEnd != *rootIn)
{
rootIn++;
}
//左子树的长度
int leftlen = rootIn-InStart;
//重建左子树
if(leftlen > 0)
{
root->_left = RebuildCode( PostStart, PostStart+leftlen-1, InStart,InStart+leftlen-1);
}
//重建右子树
if(InStart+leftlen < InEnd)
{
root->_right = RebuildCode( PostStart+leftlen, PostEnd-1, InStart+leftlen+1, InEnd);
}
return root;
}
BTreeNode* RebuildTree(int *PostOrder, int *InOrder, int len)
{
//首先判断边界条件
if(PostOrder == NULL || InOrder == NULL || len <= 0)
{
return NULL;
}
else
{
return RebuildCode(PostOrder, PostOrder+len-1, InOrder, InOrder+len-1);
}
}
//后序遍历输出二叉树序列
void PreOrder(BTreeNode *root)
{
if(root != NULL)
{
cout<_value<<" ";
}
if(root->_left != NULL)
{
PreOrder(root->_left);
}
if(root->_right != NULL)
{
PreOrder(root->_right);
}
}
int main()
{
int PostOrder[8] = {7,4,2,5,8,6,3,1};
int InOrder[8] = {4,7,2,1,5,3,8,6};
PreOrder(RebuildTree(PostOrder, InOrder, 8));
cout<