您的位置:首页 > 其它

41. leetcode98. Validate Binary Search Tree【验证二叉搜索树】

2018-02-01 13:15 435 查看
【题目】:

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.

Example 1:

2
/ \
1   3

Binary tree 
[2,1,3]
,
return true.

Example 2:

1
/ \
2   3

Binary tree 
[1,2,3]
,
return false.
【题意】:

给定一个二叉树,判断它是否是合法的二叉查找树(BST)
一棵BST定义为:
节点的左子树中的值要严格小于该节点的值。
节点的右子树中的值要严格大于该节点的值。
左右子树也必须是二叉查找树

【参考】:参考资料

【方法】:

1. 二叉搜索树的中序遍历结果是一个递增的有序序列,可先将中序遍历结果放在一个数组中,随后判断这个数组中的元素是否有序

2. 二叉搜索树的每个节点都有上、下界。对于根节点,可给定它的上下界分别为正、负无穷;对于根节点的左孩子节点,其上界为父节点的值,下界为负无穷;对于根节点的右孩子节点,其上界为正无穷,下界为父节点的值。

【Python代码】:

Python中可以用如下方式表示正负无穷

float("inf"), float("-inf")


1.# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class Solution:
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
inOrder_result = []
self.inOrderToArray(root,inOrder_result)

for i in range(1,len(inOrder_result)):
if inOrder_result[i-1] >= inOrder_result[i]:
return False

return True

def inOrderToArray(self, node, array):
if node:
if node.left:
self.inOrderToArray(node.left, array)
array.append(node.val)
if node.right:
self.inOrderToArray(node.right, array)
2.
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
return self.helper(root, low = float('-inf'), high = float('inf'))

def helper(self, root, low, high):
if not root:
return True
elif not root.left and not root.right:
return root.val > low and root.val < high
elif not root.left:
return self.helper(root.right, root.val, high) and root.val > low
elif not root.right:
return self.helper(root.left, low, root.val) and root.val < high
else:
return self.helper(root.left, low, root.val) and self.helper(root.right, root.val, high)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐