File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed
validate-binary-search-tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Time Complexity: O(n)
2
+ // Space Complexity: O(n)
3
+
4
+ var isValidBST = function ( root ) {
5
+ if ( root === null ) {
6
+ return true ;
7
+ }
8
+
9
+ // initialize a queue for BFS.
10
+ let queue = [ ] ;
11
+ queue . push ( { node : root , min : - Infinity , max : Infinity } ) ;
12
+
13
+ while ( queue . length > 0 ) {
14
+ // dequeue the front one.
15
+ let { node, min, max } = queue . shift ( ) ;
16
+
17
+ // check the BST for the current node.
18
+ if ( node . val <= min || node . val >= max ) {
19
+ return false ;
20
+ }
21
+
22
+ // enqueue the left child with updated min and max.
23
+ if ( node . left !== null ) {
24
+ queue . push ( { node : node . left , min : min , max : node . val } ) ;
25
+ }
26
+
27
+ // enqueue the right child with updated min and max.
28
+ if ( node . right !== null ) {
29
+ queue . push ( { node : node . right , min : node . val , max : max } ) ;
30
+ }
31
+ }
32
+
33
+ return true ;
34
+ } ;
You can’t perform that action at this time.
0 commit comments