LeetCode刷题-98——Validate Binary Search Tree(验证搜索二叉树)

链接:

点击打开链接

题目:

给定一个二叉树,判断其是否是一个有效的二叉搜索树。

一个二叉搜索树具有如下特征:

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

Example:

示例1

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

示例2

    5
   / \
  1   4
     / \
    3   6
Output: false
Explanation: The input is: [5,1,4,null,null,3,6]. The root node's value
             is 5 but its right child's value is 4.

解析:

  1. 利用搜索树的特性来验证,即左<根<右。左边所有的节点都比根节点小,右边所有的节点都比根节点大。所以每次递归传入一个最小值、一个最大值,所有节点都需满足规则。
  2. 这题实际上简化了难度,因为一般的二叉搜索树是左<=根<右,而这道题设定为左<根<右,那么就可以用中序遍历来做。这种方法思路很直接,通过中序遍历将所有的节点值存到一个数组里,然后再来判断这个数组是不是有序的。

解答:

方法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
        """
        return self.isvalidBST(root,float('inf'),float('-inf'))
    
    def isvalidBST(self, root, max,min):
        if not root:
            return True
        if root.val <= min or root.val >= max:
            return False
        return self.isvalidBST(root.left, root.val, largerThan) and \
               self.isvalidBST(root.right, lessThan, root.val)

方法2

# 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
        """
        # using inorder - binary search tree will be ascending order
        stack = []
        cur = root
        pre = None
        while len(stack) or cur:
            if cur:
                stack.append(cur)
                cur = cur.left
            else:
                p = stack.pop()
                if pre and p.val <= pre.val:
                    return False
                pre = p
                cur = p.right
        return True
参考(点击打开链接

猜你喜欢

转载自blog.csdn.net/u014135752/article/details/80726786
今日推荐