Repository navigation
Expand file tree
/
Copy pathBinaryTreeNode.js
More file actions
121 lines (94 loc) · 2.23 KB
/
Copy pathBinaryTreeNode.js
File metadata and controls
121 lines (94 loc) · 2.23 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
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
export default class BinaryTreeNode {
constructor(value = null, parent = null) {
this.left = null;
this.right = null;
this.parent = parent;
this.value = value;
}
get leftHeight() {
if (!this.left) {
return 0;
}
return this.left.height + 1;
}
get rightHeight() {
if (!this.right) {
return 0;
}
return this.right.height + 1;
}
get height() {
return Math.max(this.leftHeight, this.rightHeight);
}
get balanceFactor() {
return this.leftHeight - this.rightHeight;
}
setLeft(node) {
// Reset parent for left node since it is going to be detached.
if (this.left) {
this.left.parent = null;
}
// Attach new node to the left.
this.left = node;
// Make current node to be a parent for new left one.
if (this.left) {
this.left.parent = this;
}
return this;
}
setRight(node) {
// Reset parent for right node since it is going to be detached.
if (this.right) {
this.right.parent = null;
}
// Attach new node to the right.
this.right = node;
// Make current node to be a parent for new right one.
if (node) {
this.right.parent = this;
}
return this;
}
removeChild(nodeToRemove) {
if (this.left && this.left === nodeToRemove) {
this.left = null;
return true;
}
if (this.right && this.right === nodeToRemove) {
this.right = null;
return true;
}
return false;
}
replaceChild(nodeToReplace, replacementNode) {
if (!nodeToReplace || !replacementNode) {
return false;
}
if (this.left && this.left === nodeToReplace) {
this.left = replacementNode;
return true;
}
if (this.right && this.right === nodeToReplace) {
this.right = replacementNode;
return true;
}
return false;
}
traverseInOrder() {
let traverse = [];
// Add left node.
if (this.left) {
traverse = traverse.concat(this.left.traverseInOrder());
}
// Add root.
traverse.push(this.value);
// Add right node.
if (this.right) {
traverse = traverse.concat(this.right.traverseInOrder());
}
return traverse;
}
toString() {
return this.traverseInOrder().toString();
}
}