给定一个二叉树,判断其是否是一个有效的二叉搜索树。
假设一个二叉搜索树具有如下特征:
- 节点的左子树只包含小于当前节点的数。
- 节点的右子树只包含大于当前节点的数。
- 所有左子树和右子树自身必须也是二叉搜索树。
示例 1:
输入:
2
/ \
1 3
输出: true
示例 2:
输入:
5
/ \
1 4
/ \
3 6
输出: false
解释: 输入为: [5,1,4,null,null,3,6]。 根节点的值为 5 ,但是其右子节点值为 4 。这道题我想的解答方案是错误的,后来参考了别人的
# 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
"""
def test(root):
l=[]
if not root:
return []
l+=test(root.left)
# 类似于中序遍历
l.append(root.val)
l+=test(root.right)
return l
res=test(root)
'''左子树只包含小于该结点的数,右子树只包含大于该结点的数
即父节点永远大于左结点,小于右结点,
若是二叉搜索树,最后的列表必然是升序排列的,
故将res和排序后的res比较,不相等则不是
'''
if res!=sorted(list(set(res))):
return False
else:
return True
来源:https://www.cnblogs.com/Aprilnn/p/9589168.html