Skip to content

My_sols#1567

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

My_sols#1567
SrinivasaSupreeth wants to merge 1 commit into
super30admin:masterfrom
SrinivasaSupreeth:master

Conversation

@SrinivasaSupreeth
Copy link
Copy Markdown

leetcode_106:

Used post order traversal to identify the root node (last element).

Also inorder traversal to split the tree into left and right subtrees.

Applied DFS recursion with index boundaries to build the tree.

Constructed the right subtree before the left due to postorder order.

At last Used a hash map for fast lookup of root positions in inorder array.

Leetcode_129:

Used DFS traversal to explore all root-to-leaf paths.

Built numbers incrementally using current * 10 + node.val.

Detected leaf nodes to finalize and add path values.

Returned sums from left and right subtrees recursively.

Accumulated and returned the total sum of all root-to-leaf numbers

@super30admin
Copy link
Copy Markdown
Owner

Your solution is correct and efficient. Well done! Here are a few minor suggestions:

  1. Consider using a local variable and passing it via a nested function or using a mutable object (like a list) to avoid using self for the index. This makes the function more self-contained and avoids potential issues if the same Solution instance is reused (though the problem doesn't specify that).
    For example:

    def buildTree(self, inorder, postorder):
         idx_map = {val: i for i, val in enumerate(inorder)}
         post_idx = [len(postorder)-1]  # use a list to be mutable
    
         def helper(left, right):
             if left > right:
                 return None
             root_val = postorder[post_idx[0]]
             post_idx[0] -= 1
             root = TreeNode(root_val)
             mid = idx_map[root_val]
             root.right = helper(mid+1, right)
             root.left = helper(left, mid-1)
             return root
    
         return helper(0, len(inorder)-1)
  2. Alternatively, you can define the helper function without using self by using nonlocal (if using Python 3) but that requires defining the variable in the outer function. However, your current approach is acceptable.

  3. The code for leetcode_129.py is also correct, but note that we are only evaluating leetcode_106.py for this problem.

Overall, your solution is excellent.

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