书上的方法更简单,没有构造二叉树,直接将后序遍历顺序存在ans数组中,然后输出
#include<stdio.h>
#include<string.h>
char input[100];
struct Node
{
char ch;
Node* left;
Node* right;
};
bool ok;
Node* root;
Node* newnode(char c, Node* pl, Node* pr)
{
Node* pnd = new Node;
pnd->ch = c;
pnd->left = pl;
pnd->right = pr;
return pnd;
}
void del_tree(Node* subroot)
{
if(!subroot) return;
del_tree(subroot->left);
del_tree(subroot->right);
delete subroot;
}
char preorder[100];
char inorder[100];
char* find(char ch, char* start, char * end)
{
char* p;
for(p = start; p < end; ++p)
{
if(*p == ch)
break;
}
return p;
}
Node* build_tree(char* prestart, char* instart, int len)
{
if(len == 0)
return 0;
char* inparent = find(prestart[0], instart, instart+len);
int firstlen = inparent-instart;
// firstlen is the left subtree's 'length'
Node* left = build_tree(prestart+1, instart, firstlen);
Node* right = build_tree(prestart+firstlen+1, inparent+1, len-firstlen-1);
return newnode(prestart[0], left, right);
}
void postorder(Node* subroot)
{
if(!subroot) return;
postorder(subroot->left);
postorder(subroot->right);
putchar(subroot->ch);
}
int main()
{
//
freopen("input.txt", "r", stdin);
while(scanf("%s%s", preorder, inorder) == 2)
{
root = build_tree(preorder, inorder, strlen(preorder));
postorder(root);
del_tree(root);
putchar('\n');
}
}