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

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

2016-03-07 17:21 656 查看
[b]题目来源:[/b]

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

[b]题意分析:[/b]

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

[b]题目思路:[/b]

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

[b]代码(python):[/b]

  

# 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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: