結果例如輸入:先序ABCDE,中序BADCE
輸出:後序BDECA並打印二叉樹
A
|_B
|_C
|_D
|_E
代碼如下
#include
#include "stdio.h"
using namespace std;
class BinarytreeNode
{
public:
int data;
BinarytreeNode *left;
BinarytreeNode *right;
BinarytreeNode(int value=0, BinarytreeNode *l=NULL,BinarytreeNode *r=NULL):data(value),left(l),right(r)
{}
};
BinarytreeNode* createtree(int *in, int *pre, int n)
{
if(n==0) return NULL;
int k=0;
while(pre[0]!=in[k]){k++;}
BinarytreeNode *rootelement=new BinarytreeNode(pre[0]);//應該不會內存洩露的,程序結束時,對象調用析構函數,自動釋放
rootelement->left=createtree(pre+1,in,k);
rootelement->right=createtree(pre+k+1,in+k+1,n-k-1);
return rootelement;
}
void printelement(BinarytreeNode *element)
{
cout<data<<",";
}
void postorder(BinarytreeNode *subtree)
{
if(subtree!=NULL)
{
postorder(subtree->left);
postorder(subtree->right);
printelement(subtree);
}
}
int main()
{
int pre[7]={1,2,4,5,3,6,7};
int in[7]={4,2,5,1,6,3,7};
BinarytreeNode *element=createtree(in,pre,7);
postorder(element);
while(1);
return 0;
}
http://www.cnblogs.com/ITEagle/archive/2011/09/19/2180839.html
http://blog.csdn.net/nyist327/article/details/27736239