您的位置:首页 > 编程语言 > Python开发

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

2017-08-11 12:25 701 查看
【题目】

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)
       
       
 
 
 
 
 
  

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode Python 二叉树