Skip to content

Commit b4c6266

Browse files
authored
Create 889. Construct Binary Tree from Preorder and Postorder Traversal (#724)
2 parents ee800b8 + 9817530 commit b4c6266

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
class Solution {
2+
int preIndex = 0;
3+
unordered_map<int, int> postMap;
4+
5+
TreeNode* construct(vector<int>& preorder, vector<int>& postorder, int postStart, int postEnd) {
6+
// Base case: if no more nodes to process
7+
if (postStart > postEnd || preIndex >= preorder.size()) {
8+
return nullptr;
9+
}
10+
11+
// Create root node from current preorder value
12+
TreeNode* root = new TreeNode(preorder[preIndex++]);
13+
14+
// If we've processed all nodes or this is a leaf node
15+
if (postStart == postEnd) {
16+
return root;
17+
}
18+
19+
// Find the index of next preorder value in postorder
20+
// This will be the end of left subtree in postorder
21+
int postIndex = postMap[preorder[preIndex]];
22+
23+
// Only proceed if we found a valid index within our current range
24+
if (postIndex >= postStart && postIndex <= postEnd) {
25+
// Recursively construct left subtree
26+
// postStart to postIndex is the left subtree in postorder
27+
root->left = construct(preorder, postorder, postStart, postIndex);
28+
29+
// Recursively construct right subtree
30+
// postIndex + 1 to postEnd - 1 is the right subtree in postorder
31+
root->right = construct(preorder, postorder, postIndex + 1, postEnd - 1);
32+
}
33+
34+
return root;
35+
}
36+
37+
public:
38+
TreeNode* constructFromPrePost(vector<int>& preorder, vector<int>& postorder) {
39+
int n = postorder.size();
40+
41+
// Create map of value to index for postorder array
42+
for (int i = 0; i < n; i++) {
43+
postMap[postorder[i]] = i;
44+
}
45+
46+
return construct(preorder, postorder, 0, n - 1);
47+
}
48+
};

0 commit comments

Comments
 (0)