LeetCode 98 Validate Binary Search Tree(Python详解及实现)

【题目】

Given a binary tree, determine if it is avalid binary search tree (BST).

 

Assume a BST is defined as follows:

 

The left subtree of a node contains onlynodes with keys less than the node's key.

The right subtree of a node contains onlynodes with keys greater than the node's key.

Both the left and right subtrees must alsobe 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.

 

给定一个二叉树,判断是不是合法的二叉搜索树。

【思路】

一:递归。(当前节点值比他左子树大,比右子树小)

1. 为空返回true

2.左子树返回的合法性。考虑左子树不空的时候,那么根结点要比所有左子树上的结点大,即根结点大于左子树的最大值----左子树的右下角的结点。

3. 左子树返回为真且右子树也为真则返回真。考虑右子树时,根要比右子树的最小值小---最左左下角的结点。

 

【Python实现】

# -*-coding: utf-8 -*-
"""
Createdon Fri Aug 11 10:51:35 2017
 
@author:Administrator
"""
 
#Definition for a binary tree node.
classTreeNode(object):
     def __init__(self, x):
         self.val = x
         self.left = None
         self.right = None
 
classSolution(object):
    def isValidBST(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        return self.valid(root, None, None)
               
    def valid(self, root, min, max):
        if root == None or root.val == None:
            return True
       
        if (min is not None and root.val <=min) or (max is not None and root.val >= max):
            print(1)
            return False
       
        return self.valid(root.left, min,root.val) and self.valid(root.right, root.val, max)
   
   
       
if__name__ == '__main__':
    S = Solution()
    l1 = TreeNode(9)
    l2 = TreeNode(5)
    l3 = TreeNode(11)
    l4 = TreeNode(2)
    l5 = TreeNode(7)
    l6 = TreeNode(10)
    l7 = TreeNode(14)
    l8 = TreeNode(1)
    l9 = TreeNode(3)
    l10 = TreeNode(6)
    l11 = TreeNode(8)
    l12 = TreeNode(12)
    l13 = TreeNode(15)
   
    root = l1
   
    l1.left = l2
    l1.right = l3
   
    l2.left = l4
    l2.right = l5
    l3.left = l6
    l3.right = l7
   
    l4.left = l8
    l4.right = l9
    l5.left = l10
    l5.right = l11
    l7.left = l12
    l7.right = l13
   
    S.isValidBST(root)   

       

       

 

 

 

 

 

  

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值