Skip to content

working solution#1578

Open
avcode3 wants to merge 1 commit into
super30admin:masterfrom
avcode3:master
Open

working solution#1578
avcode3 wants to merge 1 commit into
super30admin:masterfrom
avcode3:master

Conversation

@avcode3
Copy link
Copy Markdown

@avcode3 avcode3 commented Mar 6, 2026

No description provided.

@super30admin
Copy link
Copy Markdown
Owner

Your solution demonstrates a good understanding of the recursive approach to building the binary tree from inorder and postorder traversals. However, there are areas where you can improve efficiency and avoid unnecessary operations.

Strengths:

  • The recursive logic is clear and correctly identifies the root and partitions the arrays.
  • The code handles the base case when the array is empty.

Areas for Improvement:

  1. Avoid Array Slicing: Instead of creating new arrays for each recursive call, use indices to represent the start and end of the subarrays in both inorder and postorder. This will save time and space.
  2. Use a Hash Map for Index Lookup: Precompute a mapping from value to index in the inorder array. This will allow you to find the root index in O(1) time instead of O(n) per node.
  3. Reduce Space Usage: By avoiding array slicing, you will significantly reduce the space complexity from O(n^2) to O(n) for the recursion stack and the hash map.

Here is an optimized version of your code based on these suggestions:

class Solution:
    def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
        # Create a mapping from value to index in inorder
        inorder_map = {val: idx for idx, val in enumerate(inorder)}
        post_index = [len(postorder) - 1]  # Use a mutable reference to track the current root in postorder

        def helper(start, end):
            if start > end:
                return None
            root_val = postorder[post_index[0]]
            root_index = inorder_map[root_val]
            post_index[0] -= 1
            node = TreeNode(root_val)
            # Build right subtree first because in postorder, the right subtree is just before the root
            node.right = helper(root_index + 1, end)
            node.left = helper(start, root_index - 1)
            return node

        return helper(0, len(inorder) - 1)

This version uses O(n) time and O(n) space, which is optimal.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants