重建二叉树

输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。

 1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     struct TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> in) {
13         TreeNode* t=new TreeNode(pre[0]);
14         if(pre.size()==1&&in.size()==1)
15             return t;
16         int count=0;
17         while(pre[0]!=in[count]){
18             count++;
19         }
20         vector<int> pre_l(pre.begin()+1,pre.begin()+count+1);
21         vector<int> pre_r(pre.begin()+count+1,pre.end());
22         vector<int> in_l(in.begin(),in.begin()+count);
23         vector<int> in_r(in.begin()+count+1,in.end());
24         if(!pre_l.empty())
25            t->left= reConstructBinaryTree(pre_l,in_l);
26         if(!pre_r.empty())
27             t->right=reConstructBinaryTree(pre_r,in_r);
28         return t;
29 
30     }
31 };

前序遍历第一个数为根节点,而中序遍历根节点前均为左子树,后均为右子树。之后再分别对左右子树同样处理。

原文地址:https://www.cnblogs.com/zl1991/p/4757768.html