题目:
解答:
1 /** 2 * Definition for a binary tree node. 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* buildTreeHelper(vector<int> &preorder, int ps, int pe, vector<int> &inorder, int is, int ie) 13 { 14 if ((pe - ps) < 0 || ((pe - ps) != (ie - is))) 15 { 16 return NULL; 17 } 18 19 TreeNode *root = new TreeNode(preorder[ps]); 20 21 int index = -1; 22 for (int i = is; i <= ie; i++) 23 { 24 if (inorder[i] == root->val) 25 { 26 index = i; 27 break; 28 } 29 } 30 31 if (-1 == index) 32 { 33 return root; 34 } 35 36 int leftprelen = index - is; 37 root->left = buildTreeHelper(preorder, ps + 1, ps + leftprelen, inorder, is, index - 1); 38 root->right = buildTreeHelper(preorder, ps + leftprelen + 1, pe, inorder, index + 1, ie); 39 return root; 40 } 41 TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) 42 { 43 return buildTreeHelper(preorder, 0, preorder.size() - 1, inorder, 0, inorder.size() -1); 44 } 45 };