98-验证二叉搜索树

给定一个二叉树,判断其是否是一个有效的二叉搜索树。

假设一个二叉搜索树具有如下特征:

  • 节点的左子树只包含小于当前节点的数。
  • 节点的右子树只包含大于当前节点的数。
  • 所有左子树和右子树自身必须也是二叉搜索树。

示例

示例 1:

输入:
2
/ \
1 3
输出: true

示例 2:

输入:
5
/ \
1 4
/ \
3 6
输出: false
解释: 输入为: [5,1,4,null,null,3,6]。
根节点的值为 5 ,但是其右子节点值为 4 。

解法

核心思想:中序遍历该树,得到的数列有序即可证明是一颗二叉排序树

注意:得到的数列应该无重复字符

class Solution:
def isValidBST(self, root: TreeNode) -> bool:
tree = []
def helper(root):
if not root:
return
helper(root.left)
tree.append(root.val)
helper(root.right)
helper(root)
# print(tree,sorted(tree))
# 需判断是否存在重复结点
return tree==sorted(tree) and len(set(tree))==len(tree)

相关信息

LeetCode:Discussion | Solution

-------------本文结束感谢您的阅读-------------