【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

猜你喜欢

转载自blog.csdn.net/weixin_41011942/article/details/85982514
今日推荐