[LeetCode]题解(python):098- Validate Binary Search Tree

题目来源:

  https://leetcode.com/problems/validate-binary-search-tree/


题意分析:

  给定一个二叉树,判断这个二叉树是否二叉搜索树,也就是严格按照左子树小于等于节点和右子树。


题目思路:

  树的题目,我们首先想到的就是递归的思想。这里也可以用递归来做。首先,定义一个函数get()来获得树的最大值和最小值。如果根节点大于左子树最大的值,小于右子树的最小值,并且左子树和右子树都是二叉搜索树。那么这个树是二叉搜索树。


代码(python):

  

# 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
        """
        def get(root):
            if root == None:
                return [0,0]
            if root.left != None:
                small = get(root.left)[0]
            else:
                small = root.val
            if root.right != None:
                big = get(root.right)[1]
            else:
                big = root.val
            return [small,big]
        if root == None:
            return True
        if root.left != None and get(root.left)[1] >= root.val:
            return False
        if root.right != None and get(root.right)[0] <= root.val:
            return False
        if self.isValidBST(root.left) and self.isValidBST(root.right):
            return True
        return False
View Code
原文地址:https://www.cnblogs.com/chruny/p/5251223.html