working solution#1578
Open
avcode3 wants to merge 1 commit into
Open
Conversation
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:
Areas for Improvement:
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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
No description provided.