在 Javascript AVL 樹中插入一個節點


我們可以學習如何在 AVL 樹中插入一個節點。AVL 樹中的插入與二叉查詢樹相同,我們只需要在向下移動樹時執行一個額外的步驟,稱為平衡樹。

這需要計算我們之前看到的平衡因子。根據配置,我們需要呼叫適當的旋轉方法。藉助以上解釋,這些方法非常直觀。

我們再次為遞迴呼叫建立一個類方法和一個幫助器函式 − 

示例

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

更新於: 15-Jun-2020

189 檢視

開啟您的職業

透過完成課程獲得認證

開始
廣告