DEV Community

Cover image for Rebalancing Trees
Paul Ngugi
Paul Ngugi

Posted on

Rebalancing Trees

After inserting or deleting an element from an AVL tree, if the tree becomes unbalanced, perform a rotation operation to rebalance the tree.
If a node is not balanced after an insertion or deletion operation, you need to rebalance it. The process of rebalancing a node is called rotation. There are four possible rotations: LL, RR, LR, and RL.

LL rotation: An LL imbalance occurs at a node A, such that A has a balance factor of -2 and a left child B with a balance factor of -1 or 0, as shown in Figure below (a). This type of imbalance can be fixed by performing a single right rotation at A, as shown in Figure below (b).

Image description

RR rotation: An RR imbalance occurs at a node A, such that A has a balance factor of +2 and a right child B with a balance factor of +1 or 0, as shown in Figure below (a). This type of imbalance can be fixed by performing a single left rotation at A, as shown in Figure below (b).

Image description

LR rotation: An LR imbalance occurs at a node A, such that A has a balance factor of -2 and a left child B with a balance factor of +1, as shown in Figure below (a). Assume B’s right child is C. This type of imbalance can be fixed by performing a double rotation (first a single left rotation at B and then a single right rotation at A), as shown in Figure below (b).

Image description

RL rotation: An RL imbalance occurs at a node A, such that A has a balance factor of +2 and a right child B with a balance factor of -1, as shown in Figure below (a). Assume B’s left child is C. This type of imbalance can be fixed by performing a double rotation (first a single right rotation at B and then a single left rotation at A), as shown in Figure below (b).

Image description

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay