标签:
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.empty() || in.empty()) 14 return NULL; 15 return ConstructBinaryTree(pre.begin(),pre.end()-1,in.begin(),in.end()-1); 16 } 17 struct TreeNode* ConstructBinaryTree 18 (vector<int>::iterator startPre,vector<int>::iterator endPre, 19 vector<int>::iterator startIn,vector<int>::iterator endIn){ 20 int rootValue = *startPre; 21 TreeNode* root = new TreeNode(rootValue); 22 if(startPre == endPre){ 23 if(startIn == endIn && *startPre == *startIn) 24 return root; 25 else 26 return NULL; 27 } 28 vector<int>::iterator rootInOrder = startIn; 29 while(rootInOrder <= endIn && *rootInOrder != rootValue) 30 ++rootInOrder; 31 32 if(rootInOrder == endIn && *rootInOrder != rootValue) 33 return NULL; 34 35 int leftLength = rootInOrder - startIn; 36 vector<int>::iterator leftPreEnd = startPre + leftLength; 37 if(leftLength>0) 38 root->left = ConstructBinaryTree(startPre+1,leftPreEnd,startIn,rootInOrder-1); 39 if(leftLength < endIn - startIn) 40 root->right = ConstructBinaryTree(leftPreEnd+1,endPre,rootInOrder+1,endIn); 41 42 return root; 43 } 44 };
标签:
原文地址:http://www.cnblogs.com/gaobaoru-articles/p/5236067.html