LeetCode 98. Validate Binary Search Tree

Posted 小丑进场

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 98. Validate Binary Search Tree相关的知识,希望对你有一定的参考价值。

原题

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.

 

Example 1:

    2
   / \\
  1   3

Binary tree [2,1,3], return true.

 

Example 2:

    1
   / \\
  2   3

Binary tree [1,2,3], return false.

 

解题思路

思路一:

  • 先将二叉树进行中序遍历,接着判断遍历的数据是否为递增的即可(较简单)

 

思路二:

  • 采用二叉搜索树的定义来解题(较难)
  • 难点:每个节点都得跟两个数进行比较,它必须在这两个数的范围之内,其中一个是它的父节点,另外一个是它的某个祖先节点
  • 这个树是从上往下遍历的,遍历到每个节点时,都要把它限定在一个已知的范围内,不管他下面的节点,只根据他上面的节点来找出这个范围
  • 这里我采用继承的方法,首先定义根节点的范围为正负无穷大,节点每一个左节点的最大值为它的父节点,最小值继承它父节点的最小值(右节点相似),由此就可以构造出一个递归程序。

 

 

完整代码

思路一

# 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
        """
        self.ret = []
        self.helper(root)
        for i in xrange(1, len(self.ret)):
            if self.ret[i] <= self.ret[i-1]:
                return False
        return True
        
    def helper(self, node):
        if node == None:
            return 
        self.helper(node.left)
        self.ret.append(node.val)
        self.helper(node.right)

  

 

思路二

# 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.helper(root, -float("inf"), float("inf"))
        
    def helper(self, node, low, high):
        if node == None:
            return True
        if node.val <= low or node.val >= high:
            return False
        return self.helper(node.left, low, node.val) and self.helper(node.right, node.val, high)

  

以上是关于LeetCode 98. Validate Binary Search Tree的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 98. Validate Binary Search Tree

leetcode 98 - Validate Binary Search Tree

Leetcode 98. Validate Binary Search Tree

leetcode [98]Validate Binary Search Tree

LeetCode 98. Validate Binary Search Tree

[LeetCode_98]Validate Binary Search Tree