Skip to content

Commit 3be495c

Browse files
Add solution to problem where we need to check whether a BST is valid or not in an optimized way
1 parent af3a5f5 commit 3be495c

File tree

1 file changed

+29
-1
lines changed

1 file changed

+29
-1
lines changed

src/main/java/com/pulkit/datastructures_algorithms/done/trees/CheckIfValidBST.java

+29-1
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,17 @@
11
package com.pulkit.datastructures_algorithms.done.trees;
22

3+
4+
//TODO: Optimize it more, no need for too much recursuve calls
35
public class CheckIfValidBST {
46
public static void main(String[] args) {
57
TreeNode root = createBST();
68
System.out.println(isValidBST(root));
9+
10+
TreeNode anotherRoot = createBST();
11+
System.out.println(isValidBSTV2(anotherRoot, null, null));
712
}
813

9-
public static boolean isValidBST(TreeNode node) {
14+
static boolean isValidBST(TreeNode node) {
1015
if (node == null)
1116
return true;
1217

@@ -49,6 +54,29 @@ private static Integer findMax(TreeNode node) {
4954
return Math.max(node.data, Math.max(maxInLeftSubtree, maxInRightSubtree));
5055
}
5156

57+
static boolean isValidBSTV2(TreeNode node, Integer max, Integer min) {
58+
if (node == null) {
59+
return true;
60+
}
61+
62+
if ((max != null && node.data > max) || (min != null && node.data < min)) {
63+
return false;
64+
}
65+
66+
boolean isLeftSubtreeValid = isValidBSTV2(node.leftChild, node.data, min);
67+
boolean isRightSubtreeValid = isValidBSTV2(node.rightChild, max, node.data);
68+
69+
if (!isLeftSubtreeValid || !isRightSubtreeValid) {
70+
return false;
71+
}
72+
return true;
73+
74+
/*
75+
simplified version
76+
return isLeftSubtreeValid && isRightSubtreeValid;
77+
*/
78+
}
79+
5280
public static TreeNode createBST() {
5381
TreeNode fourteen = new TreeNode(14, null, null);
5482
TreeNode six = new TreeNode(6, null, null);

0 commit comments

Comments
 (0)