Balanced binary tree
Intermediate · 9 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
A balanced tree keeps its left and right sides close to equal height at every node, so no branch becomes a long thin chain. That keeps every search, insert and delete quick, even as the data grows.
Practical use cases
- Web app: Sorted contact list stays fast. A CRM keeps contacts in a search tree. If contacts are added in alphabetical order, an unbalanced tree turns into a long chain and every lookup crawls through thousands of nodes. A self-balancing tree keeps the height small, so lookups stay quick as 1 lakh contacts arrive.
- Web app: Database indexes behind a search box. The fast search on an orders table in MySQL relies on a balanced tree index, so a lookup touches only a few pages even among crores of rows. If it became lopsided, the same search would take many more steps.
- System: AVL and red-black trees in libraries. Language libraries offer ordered maps and sets built on self-balancing trees, such as red-black trees in many standard libraries. They quietly rearrange nodes after inserts to avoid a lopsided shape. You rarely write these rotations yourself, but knowing they exist explains why ordered maps and database indexes stay quick even after millions of inserts.
The story: The Lopsided Cricket Bat Stand
Kabir's cricket coach arranged practice matches as a knock-out tournament: two teams play, the winner moves up, and so on until the final. With 8 teams that is only three rounds. The bracket looked like a neat, even tree.
Then two late teams joined, and the coach squeezed them into just one corner of the bracket. Now one corner needed five rounds of matches, while the other corner needed only two. Players from the long corner got tired and went home late. Everyone grumbled that the bracket was lopsided.
Mrs. Sharma, who loved tidy rules, announced the fix: "At every match, the two sides feeding into it should differ by at most one round. If not, shuffle the bracket." She walked through the bracket from the first matches upward, comparing the two sides at each match.
That rule is a balanced tree. And why do we care? Because in a balanced tree the longest trip from the top to the bottom stays short, so everything built on top (searching, inserting) stays fast.
How to spot this problem, and where you need it
A tree-based lookup was fast at first but slows down as data is added in a certain order, because the tree has grown long on one side.
Signs you need it
- Lookups that should take a few steps start taking hundreds, especially after inserting already sorted data.
- The tree height is close to the number of items instead of being much smaller.
- The problem says "check if balanced", "height difference at most 1" or "AVL" or "red-black".
Where to use it in a project
- Choosing ordered maps, sets and database indexes that keep themselves balanced.
- Writing a check that confirms the heights of left and right sides differ by at most one at every node.
The solution
To check balance, compute the height of each side at every node, and make sure the two differ by at most one. To keep a tree balanced, use a self-balancing kind such as AVL or red-black. After an insert or delete, these trees rotate a few nodes so the heavy side moves up. Rotations are cheap and keep the height small, so searches stay fast.
Payoff: Before: a lopsided tree needed about 1 lakh steps per lookup. After balancing: about 17 steps, however the data arrived.
Explain it like I am 8
Picture a see-saw at every junction. If the left side hangs much lower than the right, the see-saw tips over. A balanced tree is one where every see-saw is close to level: the two sides differ by at most one step.
How it works, step by step
- Height rule: at every node,
|height(left) - height(right)| <= 1, and both subtrees must be balanced too. - Work bottom-up: each node returns its height to its parent.
- If a node sees the two heights differ by more than 1, it returns a special "unbalanced" marker (like -100).
- Any parent that receives the marker passes it straight up. No more work is needed.
- If the marker never appears, the tree is balanced. One sweep, no repeated height calculations.
The code in four languages
PHP
<?php
class TreeNode {
public ?TreeNode $left = null;
public ?TreeNode $right = null;
public function __construct(public int $val) {}
}
// The example tree: 1
// / \
// 2 3
// / \ \
// 4 5 6
// /
// 7
function sampleTree(): TreeNode {
$root = new TreeNode(1);
$root->left = new TreeNode(2);
$root->right = new TreeNode(3);
$root->left->left = new TreeNode(4);
$root->left->right = new TreeNode(5);
$root->right->right = new TreeNode(6);
$root->left->right->left = new TreeNode(7);
return $root;
}
const UNBALANCED = -100;
// Returns the node's height, or UNBALANCED if any node below it is lopsided.
function check(?TreeNode $n): int {
if ($n === null) return -1;
$l = check($n->left);
if ($l === UNBALANCED) return UNBALANCED;
$r = check($n->right);
if ($r === UNBALANCED) return UNBALANCED;
if (abs($l - $r) > 1) return UNBALANCED; // see-saw tipped over
return 1 + max($l, $r);
}
function isBalanced(?TreeNode $root): bool {
return check($root) !== UNBALANCED;
}
$root = sampleTree();
echo 'Example tree balanced? ' . (isBalanced($root) ? 'yes' : 'no') . PHP_EOL; // yes
$root->left->right->left->left = new TreeNode(8); // hang 8 under node 7
echo 'After adding 8 under 7: ' . (isBalanced($root) ? 'yes' : 'no') . PHP_EOL; // noJavaScript
class TreeNode {
constructor(val) { this.val = val; this.left = null; this.right = null; }
}
// The example tree: 1
// / \
// 2 3
// / \ \
// 4 5 6
// /
// 7
function sampleTree() {
const root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
root.right.right = new TreeNode(6);
root.left.right.left = new TreeNode(7);
return root;
}
const UNBALANCED = -100;
// Returns the node's height, or UNBALANCED if any node below it is lopsided.
function check(n) {
if (n === null) return -1;
const l = check(n.left);
if (l === UNBALANCED) return UNBALANCED;
const r = check(n.right);
if (r === UNBALANCED) return UNBALANCED;
if (Math.abs(l - r) > 1) return UNBALANCED; // see-saw tipped over
return 1 + Math.max(l, r);
}
function isBalanced(root) {
return check(root) !== UNBALANCED;
}
const root = sampleTree();
console.log('Example tree balanced? ' + (isBalanced(root) ? 'yes' : 'no')); // yes
root.left.right.left.left = new TreeNode(8); // hang 8 under node 7
console.log('After adding 8 under 7: ' + (isBalanced(root) ? 'yes' : 'no')); // noJava
import java.util.*;
import java.util.stream.*;
public class Main {
static class TreeNode {
int val;
TreeNode left, right;
TreeNode(int val) { this.val = val; }
}
// The example tree: 1
// / \
// 2 3
// / \ \
// 4 5 6
// /
// 7
static TreeNode sampleTree() {
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
root.right.right = new TreeNode(6);
root.left.right.left = new TreeNode(7);
return root;
}
static final int UNBALANCED = -100;
// Returns the node's height, or UNBALANCED if any node below it is lopsided.
static int check(TreeNode n) {
if (n == null) return -1;
int l = check(n.left);
if (l == UNBALANCED) return UNBALANCED;
int r = check(n.right);
if (r == UNBALANCED) return UNBALANCED;
if (Math.abs(l - r) > 1) return UNBALANCED; // see-saw tipped over
return 1 + Math.max(l, r);
}
static boolean isBalanced(TreeNode root) {
return check(root) != UNBALANCED;
}
public static void main(String[] args) {
TreeNode root = sampleTree();
System.out.println("Example tree balanced? " + (isBalanced(root) ? "yes" : "no")); // yes
root.left.right.left.left = new TreeNode(8); // hang 8 under node 7
System.out.println("After adding 8 under 7: " + (isBalanced(root) ? "yes" : "no")); // no
}
}Go
package main
import (
"fmt"
)
type TreeNode struct {
Val int
Left, Right *TreeNode
}
// The example tree: 1
//
// / \
// 2 3
// / \ \
// 4 5 6
// /
// 7
func sampleTree() *TreeNode {
root := &TreeNode{Val: 1}
root.Left = &TreeNode{Val: 2}
root.Right = &TreeNode{Val: 3}
root.Left.Left = &TreeNode{Val: 4}
root.Left.Right = &TreeNode{Val: 5}
root.Right.Right = &TreeNode{Val: 6}
root.Left.Right.Left = &TreeNode{Val: 7}
return root
}
const unbalanced = -100
// check returns the node's height, or unbalanced if any node below it is lopsided.
func check(n *TreeNode) int {
if n == nil {
return -1
}
l := check(n.Left)
if l == unbalanced {
return unbalanced
}
r := check(n.Right)
if r == unbalanced {
return unbalanced
}
if l-r > 1 || r-l > 1 { // see-saw tipped over
return unbalanced
}
return 1 + max(l, r)
}
func isBalanced(root *TreeNode) bool {
return check(root) != unbalanced
}
func yesNo(b bool) string {
if b {
return "yes"
}
return "no"
}
func main() {
root := sampleTree()
fmt.Println("Example tree balanced?", yesNo(isBalanced(root))) // yes
root.Left.Right.Left.Left = &TreeNode{Val: 8} // hang 8 under node 7
fmt.Println("After adding 8 under 7:", yesNo(isBalanced(root))) // no
}Time: O(n) · Extra space: O(h). Each node is visited once because heights are passed up instead of recomputed. A naive version that recomputes height at every node is O(n²) for a skewed tree.
Watch out for
- Checking only the root's two sides. Every node must pass the see-saw test, not just the top one.
- Recomputing
height()from scratch at every node, which makes a lopsided tree take quadratic time. Return the height from the same recursion. - Confusing "balanced" with "perfect" or "full". A balanced tree can have missing nodes; it just cannot be badly lopsided.
Quick check
- A tree is balanced if, at every node, the heights of the two sides differ by...
- Exactly 0
- At most 1
- At most 2
- After hanging node 8 under 7, which node first breaks the rule?
- Node 5
- Node 1
- Node 7
- Why return the height and an "unbalanced" marker from one recursion?
- To make the tree shorter
- So it works only for small trees
- To avoid recalculating heights again and again