Course contentsShow
← C
Lesson 1030 of 1,21914. Data Structures in CFree lesson

Tree height and balancing concept

Tree height and balancing concept

What you'll learn: How the height of a tree affects search efficiency and why "balanced" shapes are the goal for high-performance data structures.

The skyscraper vs. the suburb

In a Binary Search Tree (BST), "height" is the number of edges from the root node to the deepest leaf. Think of height as the number of floors you have to descend to find a specific room.

If you have seven nodes, you could arrange them in two extreme ways:

  1. A Perfect Balance: A pyramid shape where every parent has two children. The height is only 2.
  2. A "Degenerate" Line: A straight line where each node has only one child. The height is 6.

In the pyramid, you can find any value in just 3 steps. In the straight line, finding the last value takes 7 steps. When a tree looks like a line, it stops acting like a fast tree and starts acting like a slow Linked List.

Why height matters

Every time you search for a value, you compare it to a node and move down one level. Therefore, the Maximum Search Time = Tree Height.

In a perfectly balanced tree, the height is logarithmic—O(log⁡n)O(\log n). This is incredibly fast; even with one million nodes, you could find any item in about 20 steps. However, if the tree becomes unbalanced (tall and thin), the time complexity degrades toward linear time—O(n)O(n).

Visualizing the imbalance

We calculate the "Balance Factor" of a node by subtracting the height of its right subtree from the height of its left subtree. If one side is much heavier than the other, the tree is "skewed."

struct Node {
    int data;
    struct Node *left;
    struct Node *right;
};

// A conceptual look at how height is calculated
int getHeight(struct Node* node) {
    if (node == NULL) return -1;
    
    int leftHeight = getHeight(node->left);
    int rightHeight = getHeight(node->right);
    
    // Height is the longest path plus the current level
    return (leftHeight > rightHeight ? leftHeight : rightHeight) + 1;
}

The goal of balancing

In standard BSTs, the order in which you insert data determines the height. If you insert sorted data (1, 2, 3, 4...), you get a worst-case "line" tree. Advanced trees, like AVL or Red-Black trees, use "rotations" to automatically shift nodes around and keep the height as short as possible, ensuring searches stay lightning-fast regardless of insertion order.

Key takeaway

A shorter, wider tree is faster than a tall, thin tree because height determines the maximum number of steps required to find, add, or delete data.