98. Validate Binary Search Tree
use bst's rule and recursion
Time complexity : O(n), since we visit each node exactly once.
Space complexity: O(n), since we keep up to the entire tree.
class Solution {
public boolean isValidBST(TreeNode root) {
return helper(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
private boolean helper(TreeNode root, long lower, long upper) {
if (root == null) return true;
if (root.val <= lower) return false;
if (root.val >= upper) return false;
return helper(root.left, lower, root.val) && helper(root.right, root.val, upper);
}
}use inorder
O(n)
O(n)
Last updated
Was this helpful?