[LeetCode] Construct Binary Tree from Inorder and Postorder Traversal

106. Construct Binary Tree from Inorder and Postorder Traversal

Given two integer arrays inorder and postorder where inorder is the inorder traversal of a binary tree and postorder is the postorder traversal of the same tree, construct and return the binary tree.

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
/**
* 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> rin;
TreeNode* helper(vector<int>& in, vector<int>& post, int il, int ir, int pl, int pr) {
if(il > ir or pl > pr) return nullptr;
TreeNode* root = new TreeNode(post[pr]);

root->left = helper(in, post, il, rin[post[pr]] - 1, pl, pl + rin[post[pr]] -1 - il);
root->right = helper(in, post, rin[post[pr]] + 1, ir, pl + rin[post[pr]] - il, pr - 1);

return root;
}
public:
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
int n = inorder.size();
for(int i = 0; i < n; i++) rin[inorder[i]] = i;

return helper(inorder, postorder, 0, n - 1, 0, n - 1);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/01/PS/LeetCode/construct-binary-tree-from-inorder-and-postorder-traversal/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.