Algorithm/src/main/java/tree/IsValidBST.java
2025-03-24 18:58:37 +08:00

53 lines
1.6 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package tree;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* 题目: 98. 验证二叉搜索树 (isValidBST)
* 描述:给你一个二叉树的根节点 root ,判断其是否是一个有效的二叉搜索树。
* 有效 二叉搜索树定义如下:
* 节点的左子树只包含 小于 当前节点的数。
* 节点的右子树只包含 大于 当前节点的数。
* 所有左子树和右子树自身必须也是二叉搜索树。
* 链接https://leetcode.cn/problems/validate-binary-search-tree/
*/
public class IsValidBST {
//递归
public boolean helper(TreeNode node, long lower, long upper) {
if (node == null) {
return true;
}
if (node.val <= lower || node.val >= upper) {
return false;
}
return helper(node.left, lower, node.val) && helper(node.right, node.val, upper);
}
public boolean isValidBST2(TreeNode root) {
return helper(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
//中序遍历
public void dfs(TreeNode root,List<Integer>list){
if(root!=null){
dfs(root.left,list);
list.add(root.val);
dfs(root.right,list);
}
}
public boolean isValidBST(TreeNode root) {
List<Integer> list = new ArrayList<>();
dfs(root, list);
// 检查中序遍历结果是否严格递增
for (int i = 1; i < list.size(); i++) {
if (list.get(i) <= list.get(i - 1)) {
return false;
}
}
return true;
}
}