[Leetcode]Validate Binary Search Tree

10 篇文章 0 订阅

Given a binary tree, determine if it is a valid binary search tree (BST).

Assume a BST is defined as follows:

  • The left subtree of a node contains only nodes with keys less than the node's key.
  • The right subtree of a node contains only nodes with keys greater than the node's key.

  • Both the left and right subtrees must also be binary search trees.
判断一颗二叉树是不是二叉查找树~ 跟上一题相似,可以利用BST的中序遍历是有序的这一性质来做~可以根据中序遍历的非递归解法,然后保存前驱结点pre,比较前驱结点pre和当前节点cur的值,判断是否满足递增关系,如果不满足,直接返回False~代码如下~
class Solution:
    # @param root, a tree node
    # @return a boolean
    def isValidBST(self, root):
        if root is None: return True
        stack, pre, cur = [], None, root
        while stack or cur:
            if cur:
                stack.append(cur)
                cur = cur.left
            else:
                cur = stack.pop()
                if pre and pre.val >= cur.val:
                    return False
                pre, cur = cur, cur.right
        return True

网上还有一种解法: 就是对于每个结点保存左右界,也就是保证结点满足它的左子树的每个结点比当前结点值小,右子树的每个结点比当前结点值大。对于根节点不用定位界,所以是无穷小到无穷大,接下来当我们往左边走时,上界就变成当前结点的值,下界不变,而往右边走时,下界则变成当前结点值,上界不变。如果在递归中遇到结点值超越了自己的上下界,则返回false,否则返回左右子树的结果
class Solution:
    # @param root, a tree node
    # @return a boolean
    def isValidBST(self, root):
        return self.isValidBSTRecur(root, 9223372036854775807, -9223372036854775808)
        
    def isValidBSTRecur(self, root, upper, lower):
        if root is None: return True
        if root.val <= lower or root.val >= upper:
            return False
        return self.isValidBSTRecur(root.left, root.val, lower) and self.isValidBSTRecur(root.right, upper, root.val)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值