-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0x03_binary_search_tree.js
More file actions
executable file
·77 lines (69 loc) · 1.62 KB
/
Copy path0x03_binary_search_tree.js
File metadata and controls
executable file
·77 lines (69 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#!/usr/bin/node
/** represents a node in the bstree */
class bst_node {
constructor(value){
this.value = value
this.right = null;
this.left = null;
}
}
/** Binary search tree class */
class BinarySearchTree {
constructor() {
this.root = null
}
insert(value){
const new_node = new bst_node(value)
if(!this.root){
this.root = new_node
return
}
let current = this.root;
while(true){
if(value < current.value){
if(!current.left){
current.left = new_node
return;
}
current = current.left
}
else if(value > current.value){
if(!current.right){
current.right = new_node
return;
}
current = current.right
}else {
//duplicate value
return
}
}
}
/**
* Binary search tree transversal
* INORDER: left->root-> right
* PREORDER: root->left->right
* POSTORDER: left->right->root
*/
print_inorder() {
const stack = [];
let current = this.root;
while(current || stack.length) {
while(current) {
stack.push(current)
current = current.left
}
current = stack.pop()
console.log(current.value)
current = current.right
}
}
}
let bst = new BinarySearchTree()
bst.insert(2)
bst.insert(23)
bst.insert(10)
bst.insert(7)
bst.insert(19)
bst.insert(1)
bst.print_inorder()