Description
Submission
/**
* 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 {
map<int, int> inorderIndex;
TreeNode* dfs(int i, int j, int x, int y, vector<int>& preorder, vector<int>& inorder) {
if(j - i < 0) return nullptr;
if(j == i) return new TreeNode(preorder[i]);
int rootIndexInorder = inorderIndex[preorder[i]];
int lenLeft = rootIndexInorder - x;
int lenRight = y - rootIndexInorder;
return new TreeNode(
preorder[i],
dfs(i + 1, i + lenLeft, x, x + lenLeft - 1, preorder, inorder),
dfs(i + lenLeft + 1, i + lenLeft + lenRight, rootIndexInorder + 1, rootIndexInorder + lenRight, preorder, inorder)
);
}
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
for(int i = 0; i < inorder.size(); ++i) {
inorderIndex[inorder[i]] = i;
}
int n = preorder.size();
return dfs(0, n-1, 0, n-1, preorder, inorder);
}
};
// range in preorder
// [i X X X X X j] X X X X
// r
// 3,[9],[20,15,7]. i, j
// r(rootIndexInorder)
// [9],3,[15,20,7] x y