我们可以学习如何在AVL树中插入节点。AVL树中的插入与BST相同,只要我们在树上向下移动,我们只需在插入过程中执行一个额外的步骤,称为平衡树。
这需要计算我们之前已经看到的平衡因子。并且根据配置,我们需要调用适当的旋转方法。在以上说明的帮助下,这些都是非常直观的。
我们再次为递归调用创建一个类方法和一个辅助函数-
insert(data) { let node = new this.Node(data); //检查树是否为空 if (this.root === null) { //插入为第一个元素 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) { //向左走! root.left = insertHelper(self, root.left, node); //检查平衡系数并执行适当的旋转 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) { //向右走!根。 right = insertHelper(self, root.right, node); //检查平衡系数并执行适当的旋转 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
我试图在二叉树中插入节点,如果我用addNode(Node root)替换方法addNode(Node Node)代码运行良好。这是因为我在第一行声明了吗?请解释一下。addNode方法由于字数限制而不完整,否则它是完整的,运行良好。
我试图在二叉树中插入节点,如果我用addNode(Node root)替换方法addNode(Node Node)代码运行良好。这是因为我在第一行声明了吗?请解释一下。addNode方法由于字数限制而不完整,否则它是完整的,运行良好。
二叉搜索树(BST)和二叉树(BT)中的插入有什么区别?我知道,在BST中,您将新节点的值与根进行比较,如果较小,则添加到其左侧,如果较大,则将其添加到根的右侧。BT的程序是否相同?如果没有,插入和移除的步骤是什么?
主要内容:src/runoob/binary/BinarySearchTreeInsert.java 文件代码:首先定义一个二分搜索树,Java 代码表示如下: public class BST < Key extends Comparable <Key >, Value > { // 树中的节点为私有的类, 外界不需要了解二分搜索树节点的具体实现 private class Node { private Key key ; private Val
几天来,我一直在使用二进制搜索树实现,我已经到了知道我的根正在通过使用我的“插入()”来填充的地步(当我使用Eclipse进行调试时,我可以看到这一点)。为什么我的其他节点不会被添加到树中? 这是我的BST课程: 这是我的Main(),最终我想在控制台中打印我的BST值,但首先我知道它们需要添加到树中: 公共类Main{
我已经验证了avl插入代码的三个来源。在计算高度的所有情况下, 根高度=1最大值(self.getHeight(root.left),self。getHeight(根(右)) 上面给出了一行。 这是我的问题,为什么我们要取左子树和右子树的最大值,并在其中添加一个?如果我们将节点添加到具有最小高度的子树中呢?在这种情况下,两者将具有相同的高度H而不是H 1。 此高度增量应添加为, 我说得对吗?如果是