已知二叉树的前序和中序遍历,重构该二叉树

这套题来自于牛客网剑指offer的第四题,由于本题涉及到了对树的递归操作,而且在边界上自己计算时犯了小错误,这里记录一下:

题目描述如下:

题目描述

输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
 
解题思路:
1.由树的先序遍历可以求树的根节点,
2.根据根节点的位置在中序遍历中找到树左右子树的元素,
3.递归1,2操作找到所有子树的结构。
 
注:
需要说明的是在重构左右子树的过程中的边界的计算,不然会造成越界或是计算错误。
 
代码如下:
 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     {
14         TreeNode *tree = reBulidBinaryTree(pre,0,pre.size()-1,in,0,in.size()-1);
15          
16         return tree;
17     }
18 public:
19    struct TreeNode* reBulidBinaryTree(vector<int> pre,int pre_start,int pre_end,vector<int> in,int in_start,int in_end)
20    {
21  
22        if(pre_start > pre_end|| in_start > in_end)
23        {
24            return NULL;
25        }
26         
27        TreeNode *root = new TreeNode(pre.at(pre_start));
28  
29        int i;
30  
31        for(i = in_start; i <= in_end; i++)
32        {
33            if(in.at(i) == pre.at(pre_start))
34            {//find the position where in order traverse value is the root of the tree
35                     root->left = reBulidBinaryTree(pre,pre_start+1,pre_start+i-in_start,in,in_start,i-1);//重构左子树
36                     root->right = reBulidBinaryTree(pre,pre_start+i-in_start+1,pre_end,in,i+1,in_end);//重构右子树
37                     break;
38            }
39        }
40  
41        return root;
42    }
43  
44 };

 

posted @ 2015-10-29 10:35  代码的搬运工  阅读(1218)  评论(0编辑  收藏  举报