From fd05f64fafa89cbd4c2a4a74e1bfe2d018279ead Mon Sep 17 00:00:00 2001 From: dksifoua Date: Sun, 22 Sep 2024 15:38:11 -0400 Subject: [PATCH] Validate Binary Search Tree - Recursive --- .../validatebinarysearchtree/Solution.java | 13 ++++++++++++ .../SolutionTest.java | 20 +++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/src/main/java/io/dksifoua/leetcode/validatebinarysearchtree/Solution.java b/src/main/java/io/dksifoua/leetcode/validatebinarysearchtree/Solution.java index 79cbeb1..08cbd6f 100644 --- a/src/main/java/io/dksifoua/leetcode/validatebinarysearchtree/Solution.java +++ b/src/main/java/io/dksifoua/leetcode/validatebinarysearchtree/Solution.java @@ -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); + } } diff --git a/src/test/java/io/dksifoua/leetcode/validatebinarysearchtree/SolutionTest.java b/src/test/java/io/dksifoua/leetcode/validatebinarysearchtree/SolutionTest.java index 68f7e52..3f13e89 100644 --- a/src/test/java/io/dksifoua/leetcode/validatebinarysearchtree/SolutionTest.java +++ b/src/test/java/io/dksifoua/leetcode/validatebinarysearchtree/SolutionTest.java @@ -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 }))); + } }