LeetCode 题解工作台
验证二叉搜索树
给你一个二叉树的根节点 root ,判断其是否是一个有效的二叉搜索树。 有效 二叉搜索树定义如下: 节点的左 子树 只包含 严格小于 当前节点的数。 节点的右子树只包含 严格大于 当前节点的数。 所有左子树和右子树自身必须也是二叉搜索树。 示例 1: 输入: root = [2,1,3] 输出: t…
4
题型
8
代码语言
3
相关题
当前训练重点
中等 · 二分·树·traversal
答案摘要
我们可以对二叉树进行递归中序遍历,如果遍历到的结果是严格升序的,那么这棵树就是一个二叉搜索树。 因此,我们使用一个变量 来保存上一个遍历到的节点,初始时 $\textit{prev} = -\infty$,然后我们递归遍历左子树,如果左子树不是二叉搜索树,直接返回 ,否则判断当前节点的值是否大于 ,如果不是,返回 ,否则更新 为当前节点的值,然后递归遍历右子树。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·树·traversal 题型思路
题目描述
给你一个二叉树的根节点 root ,判断其是否是一个有效的二叉搜索树。
有效 二叉搜索树定义如下:
- 节点的左子树只包含 严格小于 当前节点的数。
- 节点的右子树只包含 严格大于 当前节点的数。
- 所有左子树和右子树自身必须也是二叉搜索树。
示例 1:
输入:root = [2,1,3] 输出:true
示例 2:
输入:root = [5,1,4,null,null,3,6] 输出:false 解释:根节点的值是 5 ,但是右子节点的值是 4 。
提示:
- 树中节点数目范围在
[1, 104]内 -231 <= Node.val <= 231 - 1
解题思路
方法一:递归
我们可以对二叉树进行递归中序遍历,如果遍历到的结果是严格升序的,那么这棵树就是一个二叉搜索树。
因此,我们使用一个变量 来保存上一个遍历到的节点,初始时 ,然后我们递归遍历左子树,如果左子树不是二叉搜索树,直接返回 ,否则判断当前节点的值是否大于 ,如果不是,返回 ,否则更新 为当前节点的值,然后递归遍历右子树。
时间复杂度 ,空间复杂度 。其中 是二叉树的节点个数。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isValidBST(self, root: Optional[TreeNode]) -> bool:
def dfs(root: Optional[TreeNode]) -> bool:
if root is None:
return True
if not dfs(root.left):
return False
nonlocal prev
if prev >= root.val:
return False
prev = root.val
return dfs(root.right)
prev = -inf
return dfs(root)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Do you understand the properties of a valid Binary Search Tree?
- question_mark
Can you explain how recursion helps track valid ranges for nodes?
- question_mark
Will you describe the time and space complexity of this solution?
常见陷阱
外企场景- error
Not correctly maintaining the range for each node during recursion.
- error
Misunderstanding how the left and right subtrees' valid ranges differ.
- error
Failing to account for edge cases like a tree with only one node.
进阶变体
外企场景- arrow_right_alt
Check if a binary tree is a valid AVL tree (self-balancing binary search tree).
- arrow_right_alt
Determine if a binary tree is a valid Binary Search Tree with duplicate values allowed.
- arrow_right_alt
Validate a Binary Search Tree using iterative traversal techniques.