[LeetCode] Construct Binary Tree from Preorder and Postorder Traversal

889. Construct Binary Tree from Preorder and Postorder Traversal

Given two integer arrays, preorder and postorder where preorder is the preorder traversal of a binary tree of distinct values and postorder is the postorder traversal of the same tree, reconstruct and return the binary tree.

If there exist multiple answers, you can return any of them.

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
31
32
33
34
35
36
37
38
39
40
41
/**
* 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 {
TreeNode* helper(vector<int>& preorder, vector<int>& postorder, int& pre, int& post, unordered_set<int>& build) {
if(pre == preorder.size() or post == postorder.size()) return NULL;
if(preorder[pre] == postorder[post]) {
build.insert(preorder[pre]);
post++;
return new TreeNode(preorder[pre++]);
}
TreeNode* node = new TreeNode(preorder[pre]);
build.insert(preorder[pre++]);

node->left = helper(preorder,postorder,pre,post,build);
if(pre == preorder.size() or post == postorder.size()) return node;
if(build.count(postorder[post])) {
post++;
return node;
}

node->right = helper(preorder,postorder,pre,post,build);

post++;
return node;
}
public:
TreeNode* constructFromPrePost(vector<int>& preorder, vector<int>& postorder) {
int pre = 0, post = 0;
unordered_set<int> build;
return helper(preorder,postorder,pre,post,build);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/21/PS/LeetCode/construct-binary-tree-from-preorder-and-postorder-traversal/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.