Advertisement
amitsen01ei

ValidBST.java

Nov 20th, 2023
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.30 KB | Source Code | 0 0
  1. public class ValidBST {
  2.     public boolean isValidBST(TreeNode root) {
  3.         return isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE);
  4.     }
  5.  
  6.     /**
  7.      * Checks if a binary tree is a valid binary search tree (BST).
  8.      * <p>
  9.      * <b>Time Complexity:</b> O(n), where n is the number of nodes in the tree.
  10.      * As in the the worst case, we have to visit and check every node in the tree once.
  11.      * </p>
  12.      * <p>
  13.      * <b>Space Complexity:</b> O(h), where h is the height of the tree.
  14.      * This space is used by the call stack during the recursive calls.
  15.      * </p>
  16.      * @param node  the current node being checked.
  17.      * @param lower the lower bound for the value of the current node.
  18.      * @param upper the upper bound for the value of the current node.
  19.      * @return true if the subtree rooted at the given node is a valid BST, false otherwise.
  20.      */
  21.     private boolean isValidBST(TreeNode node, long lower, long upper) {
  22.         if (node == null) {
  23.             return true;
  24.         }
  25.  
  26.         if (node.val() <= lower || node.val() >= upper) {
  27.             return false;
  28.         }
  29.  
  30.         return isValidBST(node.left(), lower, node.val()) && isValidBST(node.right(), node.val(), upper);
  31.     }
  32.  
  33.     private record TreeNode(int val, TreeNode left, TreeNode right) {
  34.     }
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement