Skip to content

Commit c198b51

Browse files
committed
https://leetcode.com/problems/validate-binary-search-tree/
1 parent 2181b70 commit c198b51

File tree

2 files changed

+51
-2
lines changed

2 files changed

+51
-2
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
namespace LeetCodeSolutions.BinarySearchTree
2+
{
3+
class ValidateBinarySearchTree
4+
{
5+
public bool IsValidBST(TreeNode root)
6+
{
7+
// Use a more efficient approach with a single traversal
8+
return IsValidBST(root, long.MinValue, long.MaxValue);
9+
}
10+
11+
private bool IsValidBST(TreeNode node, long min, long max)
12+
{
13+
// Base case: empty trees are valid BSTs
14+
if (node == null)
15+
{
16+
return true;
17+
}
18+
19+
// Check if current node's value is within valid range
20+
if (node.val <= min || node.val >= max)
21+
{
22+
return false;
23+
}
24+
25+
// Recursively check left subtree (must be < node.Val) and right subtree (must be > node.Val)
26+
return IsValidBST(node.left, min, node.val) &&
27+
IsValidBST(node.right, node.val, max);
28+
}
29+
30+
[Test(Description = "https://leetcode.com/problems/validate-binary-search-tree/")]
31+
[Category("Medium")]
32+
[Category("LeetCode")]
33+
[Category("Validate Binary Search Tree")]
34+
[TestCaseSource(nameof(Input))]
35+
[Category("Binary Search Tree")]
36+
[Category("TopInterview")]
37+
public void Test1((bool Output, int?[] Input) item)
38+
{
39+
var response = this.IsValidBST(item.Input.ToTreeNode());
40+
Assert.That(response, Is.EqualTo(item.Output));
41+
}
42+
43+
public static IEnumerable<(bool Output, int?[] Input)> Input =>
44+
new List<(bool Output, int?[] Input)>()
45+
{
46+
(true, [2, 1, 3])
47+
};
48+
}
49+
}

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -137,11 +137,11 @@ The Top Interview 150 collection on Leetcode is a curated set of 150 interview q
137137
| 199 | Binary Tree Right Side View | Medium ||
138138
| 83 | Average of Levels in Binary Tree | Easy ||
139139
| 84 | Binary Tree Level Order Traversal | Medium ||
140-
| 85 | Binary Tree Zigzag Level Order Traversal | Medium | |
140+
| 103 | Binary Tree Zigzag Level Order Traversal | Medium | |
141141
| <br> Binary Search Tree<br> | | | |
142142
| 86 | Minimum Absolute Difference in BST | Easy ||
143143
| 87 | Kth Smallest Element in a BST | Medium | |
144-
| 88 | Validate Binary Search Tree | Medium | |
144+
| 98 | Validate Binary Search Tree | Medium | |
145145
| <br> Graph General<br> | | | |
146146
| 89 | Number of Islands | Medium | |
147147
| 90 | Surrounded Regions | Medium | |

0 commit comments

Comments
 (0)