Valid 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.

解题方法

将子树的最大值和最小值作为一个范围

Solution

# 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
        value = root.val
        return self.isValid(root.left, -sys.maxint, value) and self.isValid(root.right, value, sys.maxint)

    def isValid(self, root, low, high):
        if not root:
            return True
        if root.val > low and root.val < high:
            curValue = root.val
            return self.isValid(root.left, low, curValue) and self.isValid(root.right, curValue, high)
        else:
            return False

Reference