Skip to content

Done Trees-1#1734

Open
pranjay01 wants to merge 1 commit intosuper30admin:masterfrom
pranjay01:master
Open

Done Trees-1#1734
pranjay01 wants to merge 1 commit intosuper30admin:masterfrom
pranjay01:master

Conversation

@pranjay01
Copy link
Copy Markdown

No description provided.

@super30admin
Copy link
Copy Markdown
Owner

Validate BST (Problem1.py)

Your solution shows a good understanding of the recursive approach where you check each node against a range of values. However, there are several issues that need to be addressed:

  1. Syntax Errors:

    • In the condition root.val<=min or root.val=>max, the operator => is invalid. It should be >=.
    • When calling validateBST recursively, you forgot to use self. (e.g., self.validateBST).
  2. Base Case Handling:

    • Your function validateBST does not handle the case when root is None. You should add a check at the beginning: if root is None: return True. This is crucial for leaf nodes.
  3. Variable Naming:

    • Avoid using min and max as variable names because they are built-in functions in Python. Consider using low and high instead.
  4. Logic Flow:

    • You should check the current node's value first. If it is not within the range, return False immediately.
    • Then, recursively check the left subtree with updated max (set to the current node's value) and the right subtree with updated min (set to the current node's value).
    • The current code sets validateLeftNode to True initially, but if the left subtree is None, it should not affect the result. However, your code does not return the combined result of left and right checks correctly. You should return self.validateBST(root.left, min, root.val) and self.validateBST(root.right, root.val, max) after the current node check.
  5. Method Definition:

    • The recursive function validateBST is defined as an instance method, so you must call it with self.

Here is a corrected version of your code:

class Solution:
    def isValidBST(self, root: Optional[TreeNode]) -> bool:
        def validate(node, low, high):
            if node is None:
                return True
            if node.val <= low or node.val >= high:
                return False
            return validate(node.left, low, node.val) and validate(node.right, node.val, high)
        
        return validate(root, -math.inf, math.inf)

This version uses a helper function validate with parameters node, low, and high. It checks the current node against the range and then recursively checks the left and right subtrees.

VERDICT: NEEDS_IMPROVEMENT


Construct Binary Tree from Preorder and Inorder Traversal (Problem2.py)

Your solution is well-implemented and follows the standard recursive approach for this problem. Here are some strengths and areas for improvement:

Strengths:

  • You correctly used a dictionary to map inorder values to their indices, which allows for efficient root position lookup.
  • The recursive helper function is appropriately defined, and you handle base cases correctly.
  • The code is commented, which helps in understanding the logic.

Areas for Improvement:

  1. Global Variable Usage: Using a global variable (rootIndex) for tracking the preorder index might be problematic in some contexts, especially if the class is reused. Consider using an instance variable or passing the index as a parameter. However, in this context, since the buildTree method is called once per instance, it is acceptable. But note that if multiple calls are made, resetting rootIndex to 0 in buildTree is crucial, which you have done.

  2. Index Handling: The helper function parameters leftIndex and rightIndex are based on the inorder array indices. This is correct, but ensure that the initial call uses 0 and len(preorder)-1 which you have done.

  3. Edge Cases: Your solution handles the case when leftIndex > rightIndex by returning None, which is correct.

  4. Code Clarity: The code is clear, but you can improve variable names for better readability. For example, InorderIndexmap could be inorder_map or index_map to follow Python naming conventions (lowercase with underscores). Also, rootIndexInInOrder might be better as root_pos_inorder.

  5. Type Hints: You have used type hints in the function signatures, which is good practice. However, ensure consistency. The helper function could also benefit from type hints for parameters and return type.

  6. Efficiency: The solution is efficient. However, note that the recursive calls might lead to a stack overflow for very large trees (though the problem constraints are manageable). An iterative solution is possible but not necessary here.

Suggested Improvement:
You can avoid using a global variable by using a mutable object or a closure. For example, you can use a list to hold the index or use a nested function with a nonlocal variable. Alternatively, you can create an iterator for the preorder array. Here's an alternative without a global:

class Solution:
    def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
        index_map = {val: idx for idx, val in enumerate(inorder)}
        preorder_iter = iter(preorder)
        
        def helper(left, right):
            if left > right:
                return None
            root_val = next(preorder_iter)
            root = TreeNode(root_val)
            root_index = index_map[root_val]
            root.left = helper(left, root_index - 1)
            root.right = helper(root_index + 1, right)
            return root
        
        return helper(0, len(inorder) - 1)

This uses an iterator for preorder, which avoids the need for a global index variable.

Overall, your solution is correct and efficient. The minor issues do not affect the correctness or performance.

VERDICT: PASS

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