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 TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) { 13 //left-close-right-open 14 return RebuildBST(pre,vin,0,pre.size(),0,vin.size()); 15 16 } 17 TreeNode* RebuildBST(vector<int> pre,vector<int> vin,int preBegin,int preEnd,int inBegin,int inEnd) 18 { 19 if(preBegin >= preEnd || inBegin>=inEnd) return nullptr; 20 int rootCur = pre[preBegin]; 21 TreeNode* root = new TreeNode(rootCur); 22 int rootPos = 0; 23 for(rootPos = inBegin;rootPos<inEnd;rootPos++) 24 { 25 if(vin[rootPos] == rootCur) 26 { 27 break; 28 } 29 } 30 root->left = RebuildBST(pre,vin,preBegin + 1, preBegin + rootPos - inBegin + 1 ,inBegin,rootPos); 31 root->right = RebuildBST(pre,vin,preBegin + rootPos - inBegin + 1, preEnd,rootPos + 1,inEnd); 32 33 return root; 34 } 35 };
思考:
原文:https://www.cnblogs.com/Swetchine/p/11291701.html