-
Notifications
You must be signed in to change notification settings - Fork 0
/
12_binary_tree.js
60 lines (53 loc) · 1.22 KB
/
12_binary_tree.js
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
class BinaryTree {
constructor() {
this.root = null;
}
add(value) {
if (!this.root) {
this.root = new TreeNode(value);
} else {
let node = this.root;
let newNode = new TreeNode(value);
while (node) {
if (value > node.value) {
if (!node.right) {
break;
}
node = node.right;
} else {
if (!node.left) {
break;
}
node = node.left;
}
}
if (value > node.value) {
node.right = newNode;
} else {
node.left = newNode;
}
}
}
print(root = this.root) {
if (!root) {
return true;
}
console.log(root.value);
this.print(root.left);
this.print(root.right);
}
}
class TreeNode {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
const tree = new BinaryTree();
tree.add(5);
tree.add(2);
tree.add(6);
tree.add(2);
tree.add(1);
tree.print();