Leecode 0098. Validate Binary Search Tree
98. Validate Binary Search Tree
Given the root
of a binary tree, determine if it is a valid binary search tree (BST).
A valid BST is defined as follows:
- The left subtree of a node contains only nodes with keys strictly less than the node's key.
- The right subtree of a node contains only nodes with keys strictly greater than the node's key.
- Both the left and right subtrees must also be binary search trees.
Example 1:
1 | Input: root = [2,1,3] |
Example 2:
1 | Input: root = [5,1,4,null,null,3,6] |
题目大意
给定一棵二叉树的根节点 root
,判断其是否为有效的二叉搜索树(BST)。有效的 BST 需满足:
- 左子树的所有节点值均当前节点值;
- 右子树的所有节点值>当前节点值;
- 左、右子树也必须是有效的 BST。
例如:
- 输入
root = [2,1,3]
,满足 BST 条件,返回true
; - 输入
root = [5,1,4,null,null,3,6]
,右子树包含 3(小于根节点 5),返回false
。
解题思路
验证 BST 的核心是维护节点值的有效范围,确保每个节点的值都在其父节点限定的范围内。可通过深度优先搜索(DFS)实现:
- 递归参数:当前节点、允许的最小值(下界)、允许的最大值(上界)。
- 递归终止条件:若当前节点为空,返回
true
(空树是有效的 BST)。 - 节点值检查:若当前节点值≤下界或≥上界,返回
false
(违反 BST 规则)。 - 递归逻辑:
- 左子树的上界更新为当前节点值(左子树所有节点必须<当前节点值);
- 右子树的下界更新为当前节点值(右子树所有节点必须>当前节点值);
- 左右子树都有效时,当前树才有效。
代码实现
1 | class Solution { |
解法2:中序遍历
BST 的中序遍历结果是严格递增序列(左→根→右),若遍历过程中出现 “当前节点值≤前一个节点值”,则不是有效 BST。
1 | #include <climits> |
作者:灵茶山艾府
链接:https://leetcode.cn/problems/validate-binary-search-tree/solutions/2020306/qian-xu-zhong-xu-hou-xu-san-chong-fang-f-yxvh/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
All articles on this blog are licensed under CC BY-NC-SA 4.0 unless otherwise stated.