@@ -13,8 +13,6 @@ export default class BinarySearchTree {
13
13
}
14
14
15
15
public insert ( value : number ) {
16
- // TODO: Insert value into BST
17
-
18
16
// If empty tree, create root
19
17
if ( this . root === null ) {
20
18
this . root = new BNode ( value ) ;
@@ -50,8 +48,35 @@ export default class BinarySearchTree {
50
48
}
51
49
52
50
public lookup ( value : number ) {
53
- // TODO: Find value in BST
54
- console . log ( "Lookup not implemented" ) ;
51
+ let currentNode : BNode ;
52
+
53
+ if ( ! ! this . root ) {
54
+ currentNode = this . root ;
55
+ } else {
56
+ return null ;
57
+ }
58
+
59
+ while ( true ) {
60
+ // We found our value!
61
+ if ( value === currentNode . getValue ( ) ) {
62
+ return currentNode ;
63
+ }
64
+
65
+
66
+ if ( value < currentNode . getValue ( ) ) { // Value is smaller than current node
67
+ if ( ! ! currentNode . getLeft ( ) ) { // If left child exists
68
+ currentNode = currentNode . getLeft ( ) ; // Move into left child
69
+ continue ;
70
+ }
71
+ return null ; // No left child, value DNE
72
+ } else { // Value is greater than current node
73
+ if ( ! ! currentNode . getRight ( ) ) { // If right child exists
74
+ currentNode = currentNode . getRight ( ) ; // Move into right child
75
+ continue ;
76
+ }
77
+ return null ; // No right child, value DNE
78
+ }
79
+ }
55
80
}
56
81
57
82
public remove ( value : number ) {
@@ -88,7 +113,16 @@ if (import.meta.main) {
88
113
tree . insert ( 170 ) ;
89
114
tree . insert ( 15 ) ;
90
115
tree . insert ( 1 ) ;
91
- console . log ( JSON . stringify ( traverseFrom ( tree . getRoot ( ) ) ) ) ;
116
+ console . log ( 'Tree: ' , JSON . stringify ( traverseFrom ( tree . getRoot ( ) ) ) ) ;
117
+ printNode ( tree , 4 ) ;
118
+ printNode ( tree , 17 ) ;
119
+ printNode ( tree , 40 ) ;
120
+ printNode ( tree , 170 ) ;
92
121
93
122
// RUN: deno run Data-Structures/Trees/BinarySearchTree.ts
123
+ }
124
+
125
+ function printNode ( tree : BinarySearchTree , value : number ) : void {
126
+ const requestedNode = tree . lookup ( value ) ;
127
+ console . log ( 'Find' , value + ':' , ! ! requestedNode ? JSON . stringify ( requestedNode ) : 'Node not found.' ) ;
94
128
}
0 commit comments