根据二叉树的前序和中序序列来重建二叉树

根据二叉树的前序和中序序列来重建二叉树,输出其后序序列

这是面试笔试中经常遇到的问题

关键要理解在前序和中序序列中找左右子树的前序和中序序列的方法,利用递归实现

另外字符串的标准库函数要活用

[cpp]  view plain copy
  1. #include <iostream>  
  2. #include <string>  
  3. using namespace std;  
  4. struct TreeNode{  
  5.     char val;  
  6.     TreeNode *left,*right;  
  7. };  
  8. TreeNode * bulidTree(string pre,string in){  
  9.     TreeNode * root =NULL;  
  10.     if (pre.length() > 0)  
  11.     {  
  12.         root = new TreeNode;  
  13.         root->val = pre[0];  
  14.         int index = in.find(pre[0]);  
  15.         //关键要理解再先序和后序序列中找左右子树的先序和后序序列的方法,利用递归实现  
  16.         root->left = bulidTree(pre.substr(1,index),in.substr(0,index));  
  17.         root->right = bulidTree(pre.substr(index+1),in.substr(index+1));  
  18.     }  
  19.     return root;  
  20. }  
  21. void PostTraverse(TreeNode * root){  
  22.     if (root != NULL)  
  23.     {  
  24.         PostTraverse(root->left);  
  25.         PostTraverse(root->right);  
  26.         cout<<root->val;  
  27.     }  
  28. }  
  29. int main(){  
  30.     string prestr,instr;  
  31.     while(cin>>prestr>>instr){  
  32.         TreeNode * root =bulidTree(prestr,instr);  
  33.         PostTraverse(root);  
  34.         cout<<endl;  
  35.     }  
  36.     return 0;  
  37. }  

你可能感兴趣的:(根据二叉树的前序和中序序列来重建二叉树)