leetcode 每日一题 98. 验证二叉搜索树

递归

思路:

设计一个递归函数helper(root,lower,upper),判断以root为根节点,左右子树的值是否在在区间(lower,upper)之间,如果不在返回False。如果左子树在区间内,则更新右边界为左子树的val,继续递归helper判断。如果右子树在区间内,则更新左边界为右子树的val,继续递归判断。

代码:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def isValidBST(self, root: TreeNode) -> bool:
        def helper(node, lower = float('-inf'), upper = float('inf')):
            if not node:
                return True
            val = node.val
            if val <= lower or val >= upper:
                return False
            if not helper(node.right, val, upper):
                return False
            if not helper(node.left, lower, val):
                return False
            return True

        return helper(root)

中序遍历

思路:

中序遍历二叉树,如果当前节点的值比前一个节点值小则返回false。

代码:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def isValidBST(self, root: TreeNode) -> bool:
        stack, inorder = [], float('-inf')
        while stack or root:
            while root:
                stack.append(root)
                root = root.left
            root = stack.pop()
            if root.val <= inorder:
                return False
            inorder = root.val
            root = root.right
        return True

 

posted @ 2020-06-22 15:39  nil_f  阅读(124)  评论(0编辑  收藏  举报