//解法1 二叉树中序遍历
public boolean isValidBST(TreeNode root) {
if (root == null) {
return true;
}
List<Integer> list = new ArrayList<>();
inOrder(root,list);
for (int i = 0; i < list.size()-1; i++) {
if (list.get(i)>=list.get(i+1))
return false;
}
return true;
}
private void inOrder(TreeNode root, List<Integer> list) {
if (root == null) {
return;
}
inOrder(root.left, list);
list.add(root.val);
inOrder(root.right, list);
}
//解法2 利用BST本身的性质
public boolean isValidBST2(TreeNode root) {
if (root == null) {
return true;
}
return valid(root,Long.MIN_VALUE,Long.MAX_VALUE);
}
private boolean valid(TreeNode root, long minValue, long maxValue) {
if (root == null) {
return true;
}
if (root.val <= minValue || root.val >= maxValue) {
return false;
}
return valid(root.left, minValue, root.val)&&valid(root.right, root.val, maxValue);
}
Leetcode98: 验证二叉搜索树
最新推荐文章于 2025-02-18 21:34:47 发布
