Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions 889. Construct Binary Tree from Preorder and Postorder Traversal
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
class Solution {
int preIndex = 0;
unordered_map<int, int> postMap;

TreeNode* construct(vector<int>& preorder, vector<int>& postorder, int postStart, int postEnd) {
// Base case: if no more nodes to process
if (postStart > postEnd || preIndex >= preorder.size()) {
return nullptr;
}

// Create root node from current preorder value
TreeNode* root = new TreeNode(preorder[preIndex++]);

// If we've processed all nodes or this is a leaf node
if (postStart == postEnd) {
return root;
}

// Find the index of next preorder value in postorder
// This will be the end of left subtree in postorder
int postIndex = postMap[preorder[preIndex]];

// Only proceed if we found a valid index within our current range
if (postIndex >= postStart && postIndex <= postEnd) {
// Recursively construct left subtree
// postStart to postIndex is the left subtree in postorder
root->left = construct(preorder, postorder, postStart, postIndex);

// Recursively construct right subtree
// postIndex + 1 to postEnd - 1 is the right subtree in postorder
root->right = construct(preorder, postorder, postIndex + 1, postEnd - 1);
}

return root;
}

public:
TreeNode* constructFromPrePost(vector<int>& preorder, vector<int>& postorder) {
int n = postorder.size();

// Create map of value to index for postorder array
for (int i = 0; i < n; i++) {
postMap[postorder[i]] = i;
}

return construct(preorder, postorder, 0, n - 1);
}
};
Loading