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
+ }
0 commit comments