150强访谈简单

验证二叉搜索树

“验证 BST”问题的详细指南和 Python 实现。

问题陈述

简单

给定二叉树的根,确定它是否是有效的二叉搜索树(BST)。

有效的 BST 定义如下:

- 节点的左子树仅包含键严格小于该节点键的节点。

- 节点的右子树仅包含键严格大于该节点键的节点。

- 左右子树也必须是二叉搜索树。

该树被表示为一个级别顺序列表。实现函数 isValidBST(root: list) -> bool

约束条件
  • The number of nodes in the tree is in the range [1, 10000]
  • -2^31 <= Node.val <= 2^31 - 1

示例

Example 1
Input
[2,1,3]
Output
True
Explanation

The left child 1 < root 2, and right child 3 > root 2. Valid BST.

Example 2
Input
[5,1,4,None,None,3,6]
Output
False
Explanation

The right child of root is 4, which is less than 5. Also, node 3 is in the right subtree of 5 but is less than 5. Not a valid BST.

Example 3
Input
[5,4,6,None,None,3,7]
Output
False
Explanation

Node 3 is in the right subtree of 5 but has value 3 < 5. Not valid.

Need a Hint?
考虑使用树特定的数据结构,例如集合或堆。
Edge Cases to Watch
  • 空输入结构
  • 单元素输入
  • 大数值范围

准备好解决了吗?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在编辑器中打开
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推荐的 Python 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。