Calculating the balance factor in a Javascript AVL Tree

AVL tree checks the height of the left and the right sub-trees and assures that the difference is not more than 1. This difference is called the Balance Factor.

For example, in the following trees, the first tree is balanced and the next two trees are not balanced:

Balanced (BF ? 1) B A C Unbalanced (BF = 2) C B A Unbalanced (BF = -2) A B C BF = 1 - 1 = 0 BF = 2 - 0 = 2 BF = 0 - 2 = -2

In the second tree, the left subtree of C has height 2 and the right subtree has height 0, so the difference is 2. In the third tree, the right subtree of A has height 2 and the left is missing, so it is 0, and the difference is 2 again. AVL tree permits difference (balance factor) to be only 1.

Balance Factor Formula

BalanceFactor = height(left-subtree) - height(right-subtree)

If the difference in the height of left and right sub-trees is more than 1, the tree is balanced using some rotation techniques.

Implementation

Let us define the balance factor method and initialize the AVL tree class:

class AVLTree {
    constructor() {
        // Initialize a root element to null.
        this.root = null;
    }
    
    getBalanceFactor(root) {
        return this.getHeight(root.left) - this.getHeight(root.right);
    }
    
    getHeight(root) {
        let height = 0;
        if (root === null) {
            height = -1;
        } else {
            height = Math.max(this.getHeight(root.left), this.getHeight(root.right)) + 1;
        }
        return height;
    }
}

AVLTree.prototype.Node = class {
    constructor(data, left = null, right = null) {
        this.data = data;
        this.left = left;
        this.right = right;
    }
};

// Example usage
let avl = new AVLTree();

// Create nodes
let nodeA = new avl.Node(10);
let nodeB = new avl.Node(20);
let nodeC = new avl.Node(30);

// Build a simple tree: B as root, A as left child, C as right child
nodeB.left = nodeA;
nodeB.right = nodeC;

console.log("Balance factor of node B:", avl.getBalanceFactor(nodeB));
console.log("Height of left subtree:", avl.getHeight(nodeB.left));
console.log("Height of right subtree:", avl.getHeight(nodeB.right));
Balance factor of node B: 0
Height of left subtree: 0
Height of right subtree: 0

Key Points

  • Balance factor must be -1, 0, or 1 for a valid AVL tree
  • Positive balance factor means left subtree is taller
  • Negative balance factor means right subtree is taller
  • Balance factor of ±2 triggers rotation operations

Conclusion

The balance factor is crucial for maintaining AVL tree properties. It determines when rotations are needed to keep the tree balanced and ensure optimal search performance.

Updated on: 2026-03-15T23:18:59+05:30

859 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements