mirror of
https://github.com/trekhleb/javascript-algorithms.git
synced 2026-02-04 18:41:52 +08:00
100 lines
1.7 KiB
JavaScript
100 lines
1.7 KiB
JavaScript
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) {
|
|
this.left = node;
|
|
this.left.parent = this;
|
|
return this;
|
|
}
|
|
|
|
setRight(node) {
|
|
this.right = 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();
|
|
}
|
|
}
|