问题描述:给定一个二叉树的前序遍历序列和后序遍历序列,构建二叉树,然后输出二叉树的后序遍历结果。
代码如下:
#include <iostream>
using namespace std;
struct BinaryTreeNode
{
int value;
BinaryTreeNode *leftBinaryTreeNode;
BinaryTreeNode *rightBinaryTreeNode;
};
BinaryTreeNode* constructCore(int *preOrderStart,int *preOrderEnd,int *inOrderStart,int *inOrderEnd)
{
int rootValue=preOrderStart[0];
BinaryTreeNode* root=new BinaryTreeNode();
root->value=rootValue;
root->leftBinaryTreeNode=NULL;
root->rightBinaryTreeNode=NULL;
if(preOrderStart==preOrderEnd)
{
if(inOrderStart==inOrderEnd&&*preOrderStart==*inOrderStart)
return root;
else
cout<<"Invalid input"<<endl;
}
int *rootInorder=inOrderStart;
while(rootInorder<=inOrderEnd&&*rootInorder!=root->value)
++rootInorder;
if(rootInorder==inOrderEnd&&*rootInorder!=root->value)
cout<<"Invalid input"<<endl;
int leftLength=rootInorder-inOrderStart;
int *leftPreOrderEnd=preOrderStart+leftLength;
if(leftLength>0)
{//构建左子树
root->leftBinaryTreeNode=constructCore(preOrderStart+1,leftPreOrderEnd,inOrderStart,rootInorder-1);
}
if(leftLength<preOrderEnd-preOrderStart)
{//构建右子树
root->rightBinaryTreeNode=constructCore(leftPreOrderEnd+1,preOrderEnd,rootInorder+1,inOrderEnd);
}
return root;
}
BinaryTreeNode* Construct(int* preOrder, int *inOrder, int length)
{//preOrder为先序遍历序列,inOrder为中序遍历序列
if(preOrder==NULL||inOrder==NULL||length<=0)
return NULL;
else
return constructCore(preOrder,preOrder+length-1,inOrder,inOrder+length-1);
}
void postOrder(BinaryTreeNode *root)
{
if(root==NULL)
{
cout<<"Invalid Input!"<<endl;
return;
}
else
{
if(root->leftBinaryTreeNode!=NULL)
{
postOrder(root->leftBinaryTreeNode);
//cout<<root->leftBinaryTreeNode->value<<ends;
}
if(root->rightBinaryTreeNode!=NULL)
{
postOrder(root->rightBinaryTreeNode);
//cout<<root->rightBinaryTreeNode->value<<ends;
}
}
cout<<root->value<<endl;
}
int main()
{
int preOrder[8]={1,2,4,7,3,5,6,8};
int inOrder[8]={4,7,2,1,5,3,8,6};
BinaryTreeNode *root=Construct(preOrder,inOrder,8);
cout << "OK!" << endl;
postOrder(root);
//cout << "Hello world!" << endl;
return 0;
}
结果如下: