Skip to content

Bug in AVL Tree rorateLeftLeft and rotateRightRight #325

Open

Description

@cooliang101

run code

  const avl = new AvlTree();
  avl.insert(24);
  avl.insert(12);
  avl.insert(34);
  avl.insert(26);
  avl.insert(25);
  console.log(avl.toString());  // output:  25,26,34,24,34

left child 12 is modified to a duplicate value 34.

  const avl = new AvlTree();
  avl.insert(24);
  avl.insert(12);
  avl.insert(34);
  avl.insert(15);
  avl.insert(18);
  console.log(avl.toString());  // output: 12,24,12,15,18

same question.
fix code:

  rotateLeftLeft(rootNode) {
    // Detach left node from root node.
    const leftNode = rootNode.left;
    rootNode.setLeft(null);

    // Make left node to be a child of rootNode's parent.
    if (rootNode.parent) {
      rootNode.parent.replaceChild(rootNode, leftNode);
    } else if (rootNode === this.root) {
      // If root node is root then make left node to be a new root.
      this.root = leftNode;
    }

    // If left node has a right child then detach it and
    // attach it as a left child for rootNode.
    if (leftNode.right) {
      rootNode.setLeft(leftNode.right);
    }

    // Attach rootNode to the right of leftNode.
    leftNode.setRight(rootNode);
  }
  rotateRightRight(rootNode) {
    // Detach right node from root node.
    const rightNode = rootNode.right;
    rootNode.setRight(null);

    // Make right node to be a child of rootNode's parent.
    if (rootNode.parent) {
      rootNode.parent.replaceChild(rootNode, rightNode);
    } else if (rootNode === this.root) {
      // If root node is root then make right node to be a new root.
      this.root = rightNode;
    }

    // If right node has a left child then detach it and
    // attach it as a right child for rootNode.
    if (rightNode.left) {
      rootNode.setRight(rightNode.left);
    }

    // Attach rootNode to the left of rightNode.
    rightNode.setLeft(rootNode);
  }

Activity

  1. SHISME commented on Mar 20, 2019

    @SHISME

    I found the problem too

  2. oushu1tanqiang1 commented on Aug 15, 2023

    @oushu1tanqiang1

    find +1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions