验证二叉搜索树
https://leetcode.cn/problems/validate-binary-search-tree/
验证一颗二叉树 是否是 二叉搜索树
1Solution <递归> Accepted / Used 时空复杂度 O(n) O(n)
/*
static T f() {
前溯
f()
回溯
return T;
}
BST,左子树的val< 根结点的val < 右结点的val
利用中序遍历,我们可以知道搜索的顺序过程中,节点.val是升序的
我们记max为历史节点.val的最大值,,如果当前结点.val > max, 满足条件 or 当前结点.val <= max不满足,递归结束
其他细节如下:
*/
class Solution {
static long max = Long.MIN_VALUE;
static boolean f(TreeNode root) {
if(root==null) return true;
boolean b = f(root.left);
if(max>=root.val) b = false;//=也不行
max = Math.max(max,root.val);
return b&&f(root.right);
}
public boolean isValidBST(TreeNode root) {
max = Long.MIN_VALUE;
return f(root);
}
}
1Solution <递归(官方)> Accepted / Used 时空复杂度 O(n) O(n)
// 根节点也可以为两个子树的判断提供(min,val),(val,max)条件, 遍历的是先序遍历
class Solution {
public boolean isValidBST(TreeNode root) {
return f(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
public boolean f(TreeNode root, long max, long min) {
if (root == null)
return true;
if (root.val <= max || root.val >= min)
return false;
return f(root.left, max, root.val) && f(root.right, root.val, min);
}
}