Created
September 21, 2024 21:34
-
-
Save raghavddps2/7a5571d2c327620e7d0c1c951efdd039 to your computer and use it in GitHub Desktop.
Validate Binary Search Tree - Leetcode #98
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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