Python BEATS 87%+ - simple recursive method


  • 0
    A
    class Solution(object):
        def isValidBST(self, root):
            """
            :type root: TreeNode
            :rtype: bool
            """
            if root is None:
                return True 
            res, _, _ = self.helper(root)
            return res
        
        def helper(self, root):
            if root.left is None and root.right is None:
                return True, root.val, root.val
            if root.left is None:
                rtf, minVal, maxVal = self.helper(root.right)
                if rtf is False:
                    return rtf, root.val, maxVal
                else:
                    return root.val < minVal, root.val, maxVal
            if root.right is None:
                rtf, minVal, maxVal = self.helper(root.left)
                if rtf is False:
                    return rtf, minVal, root.val
                else:
                    return root.val > maxVal, minVal, root.val
            rtf1, minVal1, maxVal1 = self.helper(root.left)
            rtf2, minVal2, maxVal2 = self.helper(root.right)
            return rtf1 and rtf2 and root.val > maxVal1 and root.val < minVal2, minVal1, maxVal2

  • 0
    res, _, _ = self.helper(root)
    

    what are these underlines for?


  • 0
    A

    @jedihy "_" so that you don't need to assign any name for the temporary results - just makes it look cleaner. nothing special :)


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.