【LeetCode 中等题】51-验证二叉搜索树

题目描述:给定一个二叉树,判断其是否是一个有效的二叉搜索树。假设一个二叉搜索树具有如下特征:

  • 节点的左子树只包含小于当前节点的数。
  • 节点的右子树只包含大于当前节点的数。
  • 所有左子树和右子树自身必须也是二叉搜索树。

示例 1:

输入:
    2
   / \
  1   3
输出: true

示例 2:

输入:
    5
   / \
  1   4
     / \
    3   6
输出: false
解释: 输入为: [5,1,4,null,null,3,6]。
     根节点的值为 5 ,但是其右子节点值为 4 。

解法1。中序遍历该二叉树,所有节点的值存到一个数组里,再判断该数组是否严格升序

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

class Solution(object):
    def isValidBST(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        if not root:
            return True
        res = []
        self.tin(root, res)
        for i in range(len(res)-1):
            if res[i] >= res[i+1]:    # BST里无键值相等的节点
                return False
        return True
    
    def tin(self, root, res):
        if not root:
            return
        self.tin(root.left, res)
        res.append(root.val)
        self.tin(root.right, res)

解法2。用递归,helper函数的输入是最大最小值,递归后对于各个节点的比较值如下(I assume so),这样就可以将根节点、父节点的大小信息往下传递,不会只比较左右节点和自己的父节点的大小关系,因为有这样的测试用例:比根节点小的节点出现在右子树的叶子结点中。

  • 左子树:
    • 左边的节点(minV,maxV)=(minV,父节点的val)
    • 右边的节点(minV,maxV)=(父节点的val,父节点的父节点的val)
  • 右子树:
    • 左边的节点(minV,maxV)=(根节点的val,父节点的val)
    • 右边的节点(minV,maxV)=(父节点的val,maxV)
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def isValidBST(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        if not root:
            return True
        return self.tin(root, -1<<63, (1<<63)-1) 
    
    def tin(self, root, minV, maxV):
        if not root:
            return True
        else:
            if not minV < root.val < maxV:
                return False
            else:
                return self.tin(root.left, minV, root.val) and \
            self.tin(root.right, root.val, maxV)

解法3。中序遍历的迭代写法,用一个last变量记录上个节点,保证升序,否则返回False,正常遍历完毕则返回False

    def isValidBST(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        if not root:
            return True
        stack = []
        last = None
        while stack or root:
            while root:
                stack.append(root)
                root = root.left
            root = stack.pop()
            if last != None and last >= root.val:
                return False
            last = root.val
            root = root.right
        return True

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值