/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: unordered_map<int, int> pos;
TreeNode* build(vector<int>& preorder, vector<int>& inorder, int pl, int pr, int il, int ir) { if (pl > pr) return nullptr; int k = pos[preorder[pl]]; auto root = new TreeNode(inorder[k]); root->left = build(preorder, inorder, pl + 1, pl + k - il, il, k - 1); root->right = build(preorder, inorder, pl + k - il + 1, pr, k + 1, ir); return root; }
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) { if (preorder.empty()) return nullptr; for (int i = 0; i < inorder.size(); i ++ ) pos[inorder[i]] = i; return build(preorder, inorder, 0, preorder.size() - 1, 0, inorder.size() - 1); } };