1+ import BNode from './BinaryTreeNode.ts' ;
2+
3+
4+ export default class BinarySearchTree {
5+ private root : BNode | null ;
6+
7+ constructor ( ) {
8+ this . root = null ;
9+ }
10+
11+ public getRoot ( ) : BNode | null {
12+ return this . root ;
13+ }
14+
15+ public insert ( value : number ) {
16+ // TODO: Insert value into BST
17+
18+ // If empty tree, create root
19+ if ( this . root === null ) {
20+ this . root = new BNode ( value ) ;
21+ return this . root ;
22+ }
23+
24+ // Otherwise, traverse tree to find correct insert location
25+ let currentNode : BNode = this . root ;
26+
27+ while ( true ) {
28+ // Value is smaller than current node
29+ if ( value < currentNode . getValue ( ) ) {
30+ if ( ! currentNode . getLeft ( ) ) { // If no left node on currentNode
31+ currentNode . setLeft ( new BNode ( value ) ) ; // Create left node with value
32+ return this ;
33+ } else {
34+ currentNode = currentNode . getLeft ( ) ; // Otherwise, go into existing left node
35+ continue ; // Small optimization
36+ }
37+ }
38+
39+ // Value is greater than or equal to current node
40+ if ( value >= currentNode . getValue ( ) ) {
41+ if ( ! currentNode . getRight ( ) ) { // If no right node on currentNode
42+ currentNode . setRight ( new BNode ( value ) ) ; // Create right node with value
43+ return this ;
44+ } else {
45+ currentNode = currentNode . getRight ( ) ; // Otherwise, go into the existing right node
46+ continue ; // Small optimization
47+ }
48+ }
49+ }
50+ }
51+
52+ public lookup ( value : number ) {
53+ // TODO: Find value in BST
54+ console . log ( "Lookup not implemented" ) ;
55+ }
56+
57+ public remove ( value : number ) {
58+ // TODO: Remove from node from BST
59+ console . log ( "Remove not implemented" ) ;
60+ }
61+ }
62+
63+ function traverseFrom ( node : BNode | null ) {
64+ if ( node === null ) return ;
65+
66+ const tree = Object . create ( { } ) ;
67+ tree . value = node . getValue ( ) ;
68+ tree . left = node . getLeft ( ) === null ? null : traverseFrom ( node . getLeft ( ) ) ;
69+ tree . right = node . getRight ( ) === null ? null : traverseFrom ( node . getRight ( ) ) ;
70+ return tree ;
71+ }
72+
73+ //---------------------------------------------------------------------
74+ // ---------- MAIN PROGRAM ----------
75+ //---------------------------------------------------------------------
76+ if ( import . meta. main ) {
77+
78+ const tree = new BinarySearchTree ( ) ;
79+
80+ // 9
81+ // 4 20
82+ // 1 6 15 170
83+
84+ tree . insert ( 9 ) ;
85+ tree . insert ( 4 ) ;
86+ tree . insert ( 6 ) ;
87+ tree . insert ( 20 ) ;
88+ tree . insert ( 170 ) ;
89+ tree . insert ( 15 ) ;
90+ tree . insert ( 1 ) ;
91+ console . log ( JSON . stringify ( traverseFrom ( tree . getRoot ( ) ) ) ) ;
92+
93+ // RUN: deno run Data-Structures/Trees/BinarySearchTree.ts
94+ }
0 commit comments