Skip to content

working solution#1733

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

working solution#1733
avcode3 wants to merge 1 commit intosuper30admin: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 for the Validate BST problem is on the right track. You are using a recursive approach that checks each node against allowed min and max values, which is a standard method. However, there are a few issues to fix:

  • There is a syntax error in float(-inf). It should be float('-inf') or -float('inf'). Similarly, float(inf) should be float('inf').
  • The use of self.flag is acceptable, but consider optimizing by returning early when the tree is found to be invalid. Currently, even after setting self.flag to false, the recursion continues. You can add checks to stop the recursion once the flag is false.
  • Alternatively, you can avoid using an instance variable by having the helper function return a boolean. This would make the code more modular and avoid side effects.

Here is a revised version of your code that addresses these issues:

class Solution:
    def isValidBST(self, root: Optional[TreeNode]) -> bool:
        return self.helper(root, float('-inf'), float('inf'))
    
    def helper(self, node, min_val, max_val):
        if not node:
            return True
        if node.val <= min_val or node.val >= max_val:
            return False
        return self.helper(node.left, min_val, node.val) and self.helper(node.right, node.val, max_val)

This version is cleaner and avoids the use of an instance variable. It also stops the recursion as soon as an invalid node is found.

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