Skip to content

completed Trees-2#1577

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

completed Trees-2#1577
shinjaneegupta wants to merge 1 commit into
super30admin:masterfrom
shinjaneegupta:master

Conversation

@shinjaneegupta
Copy link
Copy Markdown

No description provided.

@super30admin
Copy link
Copy Markdown
Owner

Your solution for building a binary tree from inorder and postorder traversals is well-structured and efficient. You correctly used a hash map to store the indices of the inorder array, which allows for O(1) lookups. The recursive approach is implemented correctly, with the right subtree being built before the left subtree to align with the postorder traversal order.

Strengths:

  • The code is concise and readable.
  • You correctly identified the time and space complexity as O(n).
  • The use of a helper function with boundaries is appropriate.

Areas for Improvement:

  • Modifying the input list (postorder) by popping elements might be considered a side effect. While it works in this context, it's generally better to avoid modifying input parameters unless necessary. You could instead use a mutable object to track the current index (like a list that stores the current index) or use a class variable similar to the reference solution in C++. However, in Python, using a nonlocal variable or an instance variable would be better for clarity and to avoid side effects.
  • The variable name inorder_idx_map is descriptive, but you could consider shorter names like idx_map without losing clarity.
  • The initial call to tree uses len(postorder)-1 which is correct, but note that the postorder list is being popped, so its length changes. However, since we are only using the indices for the inorder array (which doesn't change), it is correct. But be cautious: if you were to use the length of postorder inside the recursive function, it would be wrong. In this case, it's not used.

For the other solution (sumRootToLeafNumbers), it is correct and efficient. Well done.

Overall, both solutions are correct and efficient.

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