-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbinary-tree.js
122 lines (110 loc) · 2.52 KB
/
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
class Tree {
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
}
insert(value) {
if (typeof value === "number") {
value = new Tree(value);
}
if (value.data <= this.data) {
if (this.left) {
this.left.insert(value);
} else {
this.left = value;
}
} else if (this.right) {
this.right.insert(value);
} else {
this.right = value;
}
}
findLastLeftNode(node) {
if (node.left.left) {
return this.findLastLeftChild(node.left);
}
return node;
}
remove(value, parentNode) {
if (this.data === value) {
if (!parentNode) {
this.data = null;
} else if (!this.right && !this.left) {
if (parentNode.left.data === value) {
parentNode.left = null;
} else {
parentNode.right = null;
}
} else if (!this.right) {
this.data = this.left.data;
this.left = this.left.left;
} else if (this.right.left) {
const lastLeftNode = this.findLastLeftNode(this.right);
this.data = lastLeftNode.left;
lastLeftNode.left = lastLeftNode.left.right;
} else {
this.data = this.right.data;
this.right = this.right.right;
}
} else if (value < this.data) {
this.left.remove(value, this);
} else {
this.right.remove(value, this);
}
}
contains(value) {
if (value === this.data) {
return true;
} else if (value < this.data && this.left) {
return this.left.contains(value);
} else if (value > this.data && this.right) {
return this.right.contains(value);
}
return false;
}
inOrder() {
if (this.left) {
this.left.inOrder();
}
console.log(this.data);
if (this.right) {
this.right.inOrder();
}
}
preOrder() {
console.log(this.data);
if (this.left) {
this.left.inOrder();
}
if (this.right) {
this.right.inOrder();
}
}
postOrder() {
if (this.left) {
this.left.inOrder();
}
if (this.right) {
this.right.inOrder();
}
console.log(this.data);
}
}
const binaryTree = new Tree(20);
binaryTree.insert(7);
binaryTree.insert(30);
binaryTree.insert(24);
binaryTree.insert(21);
binaryTree.insert(25);
binaryTree.insert(22);
binaryTree.insert(2);
binaryTree.insert(8);
// binaryTree.inOrder();
// binaryTree.postOrder();
// binaryTree.preOrder();
binaryTree.remove(7);
// binaryTree.remove(24);
binaryTree.remove(30);
binaryTree.remove(2);
binaryTree.inOrder();