1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) { return create(preorder,0,preorder.size()-1, inorder,0,inorder.size()-1); } TreeNode* create(vector<int>& preorder,int preStart,int preEnd, vector<int>&inorder,int inStart,int inEnd) { if (preStart > preEnd) return nullptr; int rootval = preorder[preStart]; int index = 0;
for (int i = inStart; i <= inEnd; i++) { if (rootval == inorder[i]) { index = i; break; } } int leftsize = index - inStart;
TreeNode* root = new TreeNode(rootval);
root->left = create(preorder,preStart+1,preStart+leftsize, inorder,inStart,index-1); root->right = create(preorder,preStart+leftsize+1,preEnd, inorder,index+1,inEnd); return root; } };
|