1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| class Solution { unordered_map<int,int>index; public: TreeNode* build(vector<int>& preorder, vector<int>& inorder,int pl,int pr,int il,int ir){ if(pl > pr) return nullptr; int pre_root = pl; int in_root = index[preorder[pre_root]]; TreeNode* root = new TreeNode(preorder[pre_root]); root->left = build(preorder,inorder,pl+1,pl+in_root-il,il,in_root-1); root->right = build(preorder,inorder,pl+in_root-il+1,pr,in_root+1,ir); return root; } TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) { int n = preorder.size(); for (int i = 0; i < n; ++i) { index[inorder[i]] = i; } return build(preorder, inorder, 0, n - 1, 0, n - 1); } };
|