From 98175308cf50471a65826b8167d2631d347d145c Mon Sep 17 00:00:00 2001 From: chayan das <110921638+Chayandas07@users.noreply.github.com> Date: Sun, 23 Feb 2025 17:31:33 +0530 Subject: [PATCH] Create 889. Construct Binary Tree from Preorder and Postorder Traversal --- ...Tree from Preorder and Postorder Traversal | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 889. Construct Binary Tree from Preorder and Postorder Traversal diff --git a/889. Construct Binary Tree from Preorder and Postorder Traversal b/889. Construct Binary Tree from Preorder and Postorder Traversal new file mode 100644 index 0000000..47afed3 --- /dev/null +++ b/889. Construct Binary Tree from Preorder and Postorder Traversal @@ -0,0 +1,48 @@ +class Solution { + int preIndex = 0; + unordered_map postMap; + + TreeNode* construct(vector& preorder, vector& 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& preorder, vector& 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); + } +};