Skip to content

Instantly share code, notes, and snippets.

@raghavddps2
Created September 21, 2024 21:34
Show Gist options
  • Select an option

  • Save raghavddps2/7a5571d2c327620e7d0c1c951efdd039 to your computer and use it in GitHub Desktop.

Select an option

Save raghavddps2/7a5571d2c327620e7d0c1c951efdd039 to your computer and use it in GitHub Desktop.
Validate Binary Search Tree - Leetcode #98
class Solution {
public boolean isValidBST(TreeNode root) {
return isValidBST(root, null, null);
}
/**
The key to solving this problem is that, we use low and high values and not
just depend on making sure that a particular node is greater than or less than its parent.
*/
public boolean isValidBST(TreeNode root, Integer low, Integer high) {
// Base case 1
if(root == null) {
return true;
}
// Base case 2
if((low != null && root.val <= low) || (high != null && root.val >= high)) {
return false;
}
// Recursive calls to left and right subtrees.
boolean isLeftBST = isValidBST(root.left, low, root.val);
boolean isRightBST = isValidBST(root.right, root.val, high);
// return the result.
return isLeftBST && isRightBST;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment