Leetcode 98. Validate Binary Search Tree
You are given a binary tree and need to determine if it is a valid Binary Search Tree (BST).
A valid BST is defined as follows:
true
if the binary tree is a valid BST; otherwise, return false
.left < node < right
./**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
public class Solution {
public boolean isValidBST(TreeNode root) {
return validate(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
private boolean validate(TreeNode node, long min, long max) {
// An empty tree is a valid BST
if (node == null) {
return true;
}
// The current node's value must be between min and max
if (node.val <= min || node.val >= max) {
return false;
}
// Recursively validate the left subtree and right subtree
return validate(node.left, min, node.val) && validate(node.right, node.val, max);
}
}
Each node is checked once to ensure it falls within the valid range, and the recursion stack ensures we process the entire tree efficiently.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?