Skip to content

Commit

Permalink
Validate Binary Search Tree - Recursive
Browse files Browse the repository at this point in the history
  • Loading branch information
dksifoua committed Sep 22, 2024
1 parent b175c69 commit fd05f64
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,17 @@ public boolean isValidBST(TreeNode root) {

return true;
}

public boolean isValidBSTRecursive(TreeNode root) {
return dfs(root, Long.MIN_VALUE, Long.MAX_VALUE);
}

private boolean dfs(TreeNode node, long minValue, long maxValue) {
if (node == null) return true;

if (node.getValue() <= minValue || node.getValue() >= maxValue) return false;

return dfs(node.getLeft(), minValue, (long) node.getValue())
&& dfs(node.getRight(), (long) node.getValue(), maxValue);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,38 @@ void test1() {
assertTrue(solution.isValidBST(TreeNode.build(new Integer[] { 2, 1, 3 })));
}

@Test
void test1Recursive() {
assertTrue(solution.isValidBSTRecursive(TreeNode.build(new Integer[] { 2, 1, 3 })));
}

@Test
void test2() {
assertFalse(solution.isValidBST(TreeNode.build(new Integer[] { 5, 1, 4, null, null, 3, 6 })));
}

@Test
void test2Recursive() {
assertFalse(solution.isValidBSTRecursive(TreeNode.build(new Integer[] { 5, 1, 4, null, null, 3, 6 })));
}

@Test
void test3() {
assertTrue(solution.isValidBST(TreeNode.build(new Integer[] { 2147483647 })));
}

@Test
void test3Recursive() {
assertTrue(solution.isValidBSTRecursive(TreeNode.build(new Integer[] { 2147483647 })));
}

@Test
void test4() {
assertFalse(solution.isValidBST(TreeNode.build(new Integer[] { 2, 2, 2 })));
}

@Test
void test4Recursive() {
assertFalse(solution.isValidBSTRecursive(TreeNode.build(new Integer[] { 2, 2, 2 })));
}
}

0 comments on commit fd05f64

Please sign in to comment.