面试题6 重建二叉树

题目描述

输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{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         if (pre.size() <= 0 || in.size() <= 0 || pre.size() != in.size()){
14             return NULL;
15         }
16         int i;
17         vector<int> pre1, pre2, in1, in2;
18         for (i = 0; i < in.size(); i++){
19             if (pre[0] != in[i]){
20                 in1.push_back(in[i]);
21                 pre1.push_back(pre[i + 1]);
22             }
23             else
24                 break;
25         }
26         if (i == in.size())
27             return NULL;
28         struct TreeNode *root = new TreeNode(pre[0]);
29 
30         for (int k = i + 1; k < in.size(); k++){
31             in2.push_back(in[k]);
32             pre2.push_back(pre[k]);
33         }
34 
35         root->left = reConstructBinaryTree(pre1, in1);
36         root->right = reConstructBinaryTree(pre2, in2);
37         return root;
38     }
39 };

 

 

posted @ 2016-04-04 14:30  早杰  阅读(142)  评论(0编辑  收藏  举报