Validate BST

https://leetcode.com/explore/learn/card/introduction-to-data-structure-binary-search-tree/140/introduction-to-a-bst/997/

刚开始我想直接套用recursion判定左右子树是否valid结果发现,右子树最小值小于root的情况都没法考虑。还是需要low,high bound这里。

class Solution:
    def isValidBST(self, root: TreeNode) -> bool:
        def dfs(node,low,high):
            if not node:
                return True
            if node.val <= low or node.val >= high:
                return False
            if not dfs(node.left,low,node.val):
                return False
            if not dfs(node.right,node.val,high):
                return False
            return True
        return dfs(root,float("-inf"),float("inf"))
        

Last updated

Was this helpful?