插入结点到 Javascript AVL 树
我们可以学习如何插入一个结点到 AVL 树中。在 AVL 树中的插入和在 BST 中的插入是一样的,我们只需要在插入的时候执行一个额外的步骤,即在遍历树的时候平衡树。
这需要计算平衡因子,我们之前已经看到过。并且根据配置,我们需要调用适当的旋转方法。在上述解释的帮助下,这些方法非常直观。
我们再次对递归调用创建类方法和辅助函数 -
示例
insert(data) {
let node = new this.Node(data);
// Check if the tree is empty
if (this.root === null) {
// Insert as the first element
this.root = node;
} else {
insertHelper(this, this.root, node);
}
}辅助方法
function insertHelper(self, root, node) {
if (root === null) {
root = node;
} else if (node.data < root.data) {
// Go left!
root.left = insertHelper(self, root.left, node);
// Check for balance factor and perform appropriate rotation
if (root.left !== null && self.getBalanceFactor(root) > 1) {
if (node.data > root.left.data) {
root = rotationLL(root);
} else {
root = rotationLR(root);
}
}
} else if (node.data > root.data) {
// Go Right! root.
right = insertHelper(self, root.right, node);
// Check for balance factor and perform appropriate rotation
if (root.right !== null && self.getBalanceFactor(root) < -1) {
if (node.data > root.right.data) {
root = rotationRR(root);
} else {
root = rotationRL(root);
}
}
}
return root;
}你可以使用以下代码进行测试 -
示例
let AVL = new AVLTree(); AVL.insert(10); AVL.insert(15); AVL.insert(5); AVL.insert(50); AVL.insert(3); AVL.insert(7); AVL.insert(12); AVL.inOrder();
输出
将会输出以下结果 -
3 5 7 10 12 15 50
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP