根据二叉树的前序和中序序列来重建二叉树,输出其后序序列
这是面试笔试中经常遇到的问题
关键要理解在前序和中序序列中找左右子树的前序和中序序列的方法,利用递归实现
另外字符串的标准库函数要活用
- #include <iostream>
- #include <string>
- using namespace std;
- struct TreeNode{
- char val;
- TreeNode *left,*right;
- };
- TreeNode * bulidTree(string pre,string in){
- TreeNode * root =NULL;
- if (pre.length() > 0)
- {
- root = new TreeNode;
- root->val = pre[0];
- int index = in.find(pre[0]);
- //关键要理解再先序和后序序列中找左右子树的先序和后序序列的方法,利用递归实现
- root->left = bulidTree(pre.substr(1,index),in.substr(0,index));
- root->right = bulidTree(pre.substr(index+1),in.substr(index+1));
- }
- return root;
- }
- void PostTraverse(TreeNode * root){
- if (root != NULL)
- {
- PostTraverse(root->left);
- PostTraverse(root->right);
- cout<<root->val;
- }
- }
- int main(){
- string prestr,instr;
- while(cin>>prestr>>instr){
- TreeNode * root =bulidTree(prestr,instr);
- PostTraverse(root);
- cout<<endl;
- }
- return 0;
- }