class TreeNode {
constructor(value, leftNode, rightNode) {
this.value = value;
this.leftNode = leftNode;
this.rightNode = rightNode;
}
}
class BinarySearchTree {
constructor() {
this.root = null;
}
create() {
let length = 10;
for (let i = 0; i < length; i++) {
let value = Math.trunc(Math.random() * 10);
this.root = this.insert(this.root, value);
}
}
insert(root, value) {
if (root == null) {
return new TreeNode(value, null, null);
}
if (root.value >= value) {
root.leftNode = this.insert(root.leftNode, value);
}
if (root.value < value) {
root.rightNode = this.insert(root.rightNode, value);
}
return root;
}
display(root) {
if (root == null) {
return;
}
this.display(root.leftNode);
console.log(root.value);
this.display(root.rightNode);
}
find(root, value) {
if (root == null) {
return null;
}
if (root.value > value) {
return this.find(root.leftNode, value);
}
if (root.value < value) {
return this.find(root.rightNode, value);
}
if (root.value == value) {
console.log("找到节点:" + root.value);
return root;
}
return null;
}
remove(root, value) {
if (root == null) {
return null;
}
if (root.value > value) {
root.leftNode = this.remove(root.leftNode, value);
return root;
}
if (root.value < value) {
root.rightNode = this.remove(root.rightNode, value);
return root;
}
if (!root.leftNode && !root.rightNode) {
return null;
} else if (!root.leftNode) {
return root.rightNode;
} else if (!root.rightNode) {
return root.leftNode;
} else {
let node = root.rightNode;
while (node.leftNode) {
node = node.leftNode;
}
root.value = node.value;
root.rightNode = this.remove(root.rightNode, node.value);
return root;
}
}
}
const binarySearchTree = new BinarySearchTree();
binarySearchTree.create();
binarySearchTree.display(binarySearchTree.root);
let findValue = 3;
let node = binarySearchTree.find(binarySearchTree.root, findValue);
if (node) {
console.log(`存在值为${findValue}的节点`);
binarySearchTree.remove(binarySearchTree.root, findValue);
binarySearchTree.display(binarySearchTree.root);
} else {
console.log(`不存在值为${findValue}的节点`);
}
module.exports.tree = binarySearchTree.root;