<span>重建二叉树</span>
题目描述
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{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.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 };