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 {
unordered_map<int, int> inorderIndex;
TreeNode* dfs(int i, int j, int x, int y, vector<int>& inorder, vector<int>& postorder) {
if(j < i) return nullptr;
if(j == i) return new TreeNode(inorder[i]);
int rootVal = postorder[y];
int inorderRootIndex = inorderIndex[rootVal];
// for inorder
int lenLeft = inorderRootIndex - i;
int lenRight = j - inorderRootIndex;
return new TreeNode(
rootVal,
dfs(i, inorderRootIndex - 1, x, x + lenLeft - 1, inorder, postorder),
dfs(inorderRootIndex + 1, inorderRootIndex + lenRight, y - lenRight, y - 1, inorder, postorder)
);
}
public:
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
int n = inorder.size();
for(int i = 0; i < n; ++i) {
inorderIndex[inorder[i]] = i;
}
return dfs(0, n-1, 0, n-1, inorder, postorder);
}
};
// [9],3,[15,20,7]