g0001_0100.s0098_validate_binary_search_tree.Solution Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java21 Show documentation
Show all versions of leetcode-in-java21 Show documentation
Java-based LeetCode algorithm problem solutions, regularly updated
package g0001_0100.s0098_validate_binary_search_tree;
// #Medium #Top_100_Liked_Questions #Top_Interview_Questions #Depth_First_Search #Tree #Binary_Tree
// #Binary_Search_Tree #Data_Structure_I_Day_14_Tree #Level_1_Day_8_Binary_Search_Tree
// #Udemy_Tree_Stack_Queue #Big_O_Time_O(N)_Space_O(log(N))
// #2022_06_21_Time_0_ms_(100.00%)_Space_43.4_MB_(72.88%)
import com_github_leetcode.TreeNode;
/*
* 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;
* }
* }
*/
/**
* 98 - Validate Binary Search Tree\.
*
* Medium
*
* Given the `root` of a binary tree, _determine if it is a valid binary search tree (BST)_.
*
* A **valid BST** is defined as follows:
*
* * The left subtree of a node contains only nodes with keys **less than** the node's key.
* * The right subtree of a node contains only nodes with keys **greater than** the node's key.
* * Both the left and right subtrees must also be binary search trees.
*
* **Example 1:**
*
* ![](https://assets.leetcode.com/uploads/2020/12/01/tree1.jpg)
*
* **Input:** root = [2,1,3]
*
* **Output:** true
*
* **Example 2:**
*
* ![](https://assets.leetcode.com/uploads/2020/12/01/tree2.jpg)
*
* **Input:** root = [5,1,4,null,null,3,6]
*
* **Output:** false
*
* **Explanation:** The root node's value is 5 but its right child's value is 4.
*
* **Constraints:**
*
* * The number of nodes in the tree is in the range [1, 104]
.
* * -231 <= Node.val <= 231 - 1
**/
public class Solution {
public boolean isValidBST(TreeNode root) {
return solve(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
// we will send a valid range and check whether the root lies in the range
// and update the range for the subtrees
private boolean solve(TreeNode root, long left, long right) {
if (root == null) {
return true;
}
if (root.val <= left || root.val >= right) {
return false;
}
return solve(root.left, left, root.val) && solve(root.right, root.val, right);
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy