返回
JS算法探秘:平衡二叉树之奥秘与算法实现
前端
2024-01-17 22:01:47
平衡二叉树的魅力与作用
平衡二叉树是一种独特的二叉树数据结构,它以其卓越的性能和广泛的应用赢得程序员的青睐。平衡二叉树严格遵循一种特定的约束:任意节点的左右子树高度差绝对值不超过1,这确保了它具有出色的查询和插入性能。
平衡二叉树的算法实现
为了让您更深入地了解平衡二叉树,我们为您提供了一种清晰易懂的JS算法实现:
class Node {
constructor(key, value) {
this.key = key;
this.value = value;
this.left = null;
this.right = null;
}
}
class BinarySearchTree {
constructor() {
this.root = null;
}
insert(key, value) {
const newNode = new Node(key, value);
if (this.root === null) {
this.root = newNode;
} else {
this._insert(newNode, this.root);
}
}
_insert(newNode, currentNode) {
if (newNode.key < currentNode.key) {
if (currentNode.left === null) {
currentNode.left = newNode;
} else {
this._insert(newNode, currentNode.left);
}
} else {
if (currentNode.right === null) {
currentNode.right = newNode;
} else {
this._insert(newNode, currentNode.right);
}
}
}
search(key) {
return this._search(key, this.root);
}
_search(key, currentNode) {
if (currentNode === null) {
return null;
}
if (key === currentNode.key) {
return currentNode.value;
} else if (key < currentNode.key) {
return this._search(key, currentNode.left);
} else {
return this._search(key, currentNode.right);
}
}
delete(key) {
this.root = this._delete(key, this.root);
}
_delete(key, currentNode) {
if (currentNode === null) {
return null;
}
if (key < currentNode.key) {
currentNode.left = this._delete(key, currentNode.left);
} else if (key > currentNode.key) {
currentNode.right = this._delete(key, currentNode.right);
} else {
if (currentNode.left === null) {
return currentNode.right;
} else if (currentNode.right === null) {
return currentNode.left;
}
const successor = this._getSuccessor(currentNode);
currentNode.key = successor.key;
currentNode.value = successor.value;
currentNode.right = this._delete(successor.key, currentNode.right);
}
return currentNode;
}
_getSuccessor(currentNode) {
let successor = currentNode.right;
while (successor.left !== null) {
successor = successor.left;
}
return successor;
}
isBalanced() {
return this._isBalanced(this.root);
}
_isBalanced(currentNode) {
if (currentNode === null) {
return true;
}
const leftHeight = this._getHeight(currentNode.left);
const rightHeight = this._getHeight(currentNode.right);
if (Math.abs(leftHeight - rightHeight) > 1) {
return false;
}
return this._isBalanced(currentNode.left) && this._isBalanced(currentNode.right);
}
_getHeight(currentNode) {
if (currentNode === null) {
return 0;
}
return 1 + Math.max(this._getHeight(currentNode.left), this._getHeight(currentNode.right));
}
}
结语
平衡二叉树以其出色的性能和广泛的应用赢得了程序员的青睐,它不仅可以提高查询和插入的效率,而且在许多领域都有着重要的作用。通过本文的讲解,您已经掌握了平衡二叉树的奥秘和JS算法实现,希望它能成为您编程生涯中的利器,帮助您轻松应对各种编程挑战。