Hello coders, In this blog, I’ll give a solution for another Leetcode Problem which is ” Validate Binary Search Leetcode Solution”.
Let’s see the problem statement to understand the problem clearly.
Problem statement:
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.
Validate Binary Search Leetcode Solution in Java
//Validate Binary Search Leetcode Solution in Java class Solution { public boolean isValidBST(TreeNode root) { return isValidBST(root, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY); } private boolean isValidBST(TreeNode root, double min, double max) { if (root.val <= min || root.val >= max) return false; if (root.left != null) { if (!isValidBST(root.left, min, root.val)) return false; } if (root.right != null) { if (!isValidBST(root.right, root.val, max)) return false; } return true; } } //Validate Binary Search Leetcode Solution in Java
Disclaimer: This problem(Validate Binary Search Leetcode solution) is originally created by Leetcode. Codesagar only provides a solution for it. This solution is only for Educational and learning purposes.