标签:
这套题来自于牛客网剑指offer的第四题,由于本题涉及到了对树的递归操作,而且在边界上自己计算时犯了小错误,这里记录一下:
题目描述如下:
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 };
标签:
原文地址:http://www.cnblogs.com/daimadebanyungong/p/4919665.html