mirror of
https://github.com/trekhleb/javascript-algorithms.git
synced 2026-03-13 08:51:02 +08:00
Add binary search tree.
This commit is contained in:
37
src/data-structures/tree/BinaryTreeNode.js
Normal file
37
src/data-structures/tree/BinaryTreeNode.js
Normal file
@@ -0,0 +1,37 @@
|
||||
export default class BinaryTreeNode {
|
||||
constructor(value = null, left = null, right = null) {
|
||||
this.left = left;
|
||||
this.right = right;
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
addLeft(node) {
|
||||
this.left = node;
|
||||
return this;
|
||||
}
|
||||
|
||||
addRight(node) {
|
||||
this.right = node;
|
||||
return this;
|
||||
}
|
||||
|
||||
hasLeft() {
|
||||
return !!this.left;
|
||||
}
|
||||
|
||||
hasRight() {
|
||||
return !!this.right;
|
||||
}
|
||||
|
||||
traverseInOrder() {
|
||||
return Array.prototype.concat(
|
||||
this.left ? this.left.traverseInOrder() : [null],
|
||||
[this.value],
|
||||
this.right ? this.right.traverseInOrder() : [null],
|
||||
);
|
||||
}
|
||||
|
||||
toString() {
|
||||
return this.traverseInOrder().filter(value => !!value).toString();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user