Skip to lesson

Height, diameter and balance

Tree measurements assess depth, spanning distances, and structural balance using recursive bottom-up calculations.

Measuring Height and Maximum Depth

The height of a tree is the number of edges on the longest path from the root down to a leaf. A single node has height 0.

The height of a node is 1 plus the larger height of its two children, and a missing child counts as 0. The code finds the maximum depth of a five-node tree.

Example 1 · Computing Maximum Depth of a Binary Tree

MaxDepthDemo.javaJava
public class MaxDepthDemo {    static class TreeNode {        int val;        TreeNode left, right;        TreeNode(int v) { val = v; }    }
    public static int maxDepth(TreeNode root) {        if (root == null) return 0;        return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));    }
    public static void main(String[] args) {        TreeNode root = new TreeNode(3);        root.left = new TreeNode(9);        root.right = new TreeNode(20);        root.right.left = new TreeNode(15);        root.right.right = new TreeNode(7);
        System.out.println("Max depth: " + maxDepth(root));    }}
Output
Max depth: 3

What this code does

  • Returns 0 when encountering a null reference as base case.
  • Recursively computes 1 plus the maximum depth between subtrees.

The maximum depth of a binary tree is the longest path length from root to leaf. We compute height recursively using divide and conquer. The base case returns 0 when encountering a null node pointer. For any node, its height equals 1 plus the maximum of its left and right subtrees.

The formula is height(node) = 1 + Math.max(height(node.left), height(node.right)). This bottom-up calculation processes child subtrees before combining their heights at the parent. Every node is visited once, taking linear O(n) time. The call stack consumes O(h) space, where h is the tree height. Trace height on a three-node tree. Child 2 has null children: height is 1 + max(0, 0) = 1. Child 3 has null children: height is 1 + max(0, 0) = 1. Root 1 combines subtrees: height is 1 + max(1, 1) = 2. The tree has a maximum depth of 2.

Computing the Diameter of a Binary Tree

The diameter of a tree is the number of edges on the longest path between any two of its nodes. The path need not pass through the root.

The diameter is the longest path between any two nodes, counted in edges. It does not have to pass through the root. The code finds it in one pass.

Example 2 · Brute force: height at every node (O(n²) time, O(h) space)

DiameterBruteDemo.javaJava
public class DiameterBruteDemo {    static class TreeNode {        int val;        TreeNode left, right;        TreeNode(int v) { val = v; }    }
    static int height(TreeNode node) {        if (node == null) return 0;        return 1 + Math.max(height(node.left), height(node.right));    }
    static int diameter(TreeNode node) {        if (node == null) return 0;        int through = height(node.left) + height(node.right);        return Math.max(through, Math.max(diameter(node.left), diameter(node.right)));    }
    public static void main(String[] args) {        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);
        System.out.println("Diameter: " + diameter(root));    }}
Output
Diameter: 3

What this code does

  • diameter asks, at every node, for the longest path through it (left height plus right height) and compares it with the best path in each subtree.
  • It is correct but slow: height walks a whole subtree, and it is called again at every ancestor. On a long chain that is about n + (n-1) + ... steps, so O(n²).

Example 3 · Optimal: one postorder pass (O(n) time, O(h) space)

DiameterDemo.javaJava
public class DiameterDemo {    static class TreeNode {        int val;        TreeNode left, right;        TreeNode(int v) { val = v; }    }
    private static int maxDiameter = 0;
    public static int diameterOfBinaryTree(TreeNode root) {        maxDiameter = 0;        height(root);        return maxDiameter;    }
    private static int height(TreeNode node) {        if (node == null) return 0;        int left = height(node.left);        int right = height(node.right);        maxDiameter = Math.max(maxDiameter, left + right);        return 1 + Math.max(left, right);    }
    public static void main(String[] args) {        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);
        System.out.println("Diameter: " + diameterOfBinaryTree(root));    }}
Output
Diameter: 3

What this code does

  • Calculates longest path through current node as left plus right heights.
  • Updates global diameter tracker while returning height up the call stack.
  • Why it is faster: each node's height is calculated once and handed to its parent, instead of being recomputed from scratch at every ancestor.

The diameter of a binary tree is the length of the longest path between any two nodes. Crucially, this longest path does not necessarily need to pass through the root node. The path length is defined as the number of edges connecting the two endpoint nodes. A naive approach computes height at every node, taking quadratic O(n²) time.

We can compute the diameter in optimal linear O(n) time during a single postorder pass. For any node, the longest path passing through it equals leftHeight + rightHeight. We maintain an external diameter variable updated at every node. Meanwhile, the recursive function returns 1 + max(leftHeight, rightHeight) to its parent. Trace diameter on a five-node tree. Subtree at node 2 has left height 1 and right height 1. Path through node 2 is 1 + 1 = 2 edges between leaves 4 and 5. At root node 1, left height is 2 and right height 1. Path through root 1 is 2 + 1 = 3 edges between leaf 4 and leaf 3. Maximum diameter is 3.

Checking Tree Balance in Optimal Linear Time

A height-balanced tree is a tree in which, for every node, the heights of the left and right subtrees differ by at most 1.

A tree is height-balanced when every node's two subtrees differ in height by at most 1. The code checks this in one pass and returns -1 at the first unbalanced node.

Example 4 · Brute force: height of both sides at every node (O(n²) time, O(h) space)

BalancedBruteDemo.javaJava
public class BalancedBruteDemo {    static class TreeNode {        int val;        TreeNode left, right;        TreeNode(int v) { val = v; }    }
    static int height(TreeNode node) {        if (node == null) return 0;        return 1 + Math.max(height(node.left), height(node.right));    }
    static boolean isBalanced(TreeNode node) {        if (node == null) return true;        int difference = Math.abs(height(node.left) - height(node.right));        return difference <= 1 && isBalanced(node.left) && isBalanced(node.right);    }
    public static void main(String[] args) {        TreeNode root = new TreeNode(1);        root.left = new TreeNode(2);        root.right = new TreeNode(2);        root.left.left = new TreeNode(3);        root.left.right = new TreeNode(3);        root.left.left.left = new TreeNode(4);
        System.out.println("Is balanced: " + isBalanced(root));    }}
Output
Is balanced: false

What this code does

  • At every node the code measures both subtree heights, then repeats the whole check for each child.
  • The same subtrees are measured again and again as the recursion goes down, which costs O(n²) on a chain-shaped tree.

Example 5 · Optimal: height and balance in one pass (O(n) time, O(h) space)

BalancedCheckDemo.javaJava
public class BalancedCheckDemo {    static class TreeNode {        int val;        TreeNode left, right;        TreeNode(int v) { val = v; }    }
    public static boolean isBalanced(TreeNode root) {        return checkHeight(root) != -1;    }
    private static int checkHeight(TreeNode node) {        if (node == null) return 0;        int left = checkHeight(node.left);        if (left == -1) return -1;        int right = checkHeight(node.right);        if (right == -1) return -1;
        if (Math.abs(left - right) > 1) return -1;        return 1 + Math.max(left, right);    }
    public static void main(String[] args) {        TreeNode root = new TreeNode(1);        root.left = new TreeNode(2);        root.right = new TreeNode(2);        root.left.left = new TreeNode(3);        root.left.right = new TreeNode(3);        root.left.left.left = new TreeNode(4);
        System.out.println("Is balanced: " + isBalanced(root));    }}
Output
Is balanced: false

What this code does

  • Returns -1 immediately whenever a subtree fails the balance condition.
  • Short-circuits redundant recursion when an unbalanced subtree is discovered.
  • Why it is faster: the height travels up with the balance answer, so no subtree is measured twice, and -1 stops the work early.

A binary tree is height-balanced if for every node, the height difference is at most 1. Formally, Math.abs(leftHeight - rightHeight) <= 1 for all subtrees. A naive approach calls height() on each node, taking slow quadratic O(n²) time. This repeats redundant subtree traversals at every level of the tree.

An optimal bottom-up check computes balance and height simultaneously in O(n) time. If a subtree is balanced, the function returns its positive height. If any subtree is unbalanced, it returns -1 immediately as an error signal. When a parent sees -1 from either child, it propagates -1 upward without further checks. Trace balance check on a skewed tree with three nodes. Node 3 has left 0 and right 0: height is 1. Node 2 has left 1 and right 0: height is 2 (difference is 1, balanced). Node 1 has left 2 and right 0: height difference is 2 - 0 = 2 (> 1). Node 1 detects unbalance and returns -1, confirming the tree is unbalanced.

Fix the error

Fix the compile error

Read the real compiler error, then pick the line that fixes it.

Round 1 of 2

check returns the height, or -1 when the tree is unbalanced.

public class BalanceFix {
static class Node { int val; Node left, right; Node(int v) { val = v; } }
static int check(Node n) {
if (n == null) return 0;
int l = check(n.left), r = check(n.right);
if (l == -1 || r == -1 || Math.abs(l - r) > 1) return -1;
return 1 + Math.max(l, r);
}
static boolean isBalanced(Node root) {
return check(root);
}
public static void main(String[] args) { System.out.println(isBalanced(new Node(1))); }
}

Error

BalanceFix.java:10: error: incompatible types: int cannot be converted to boolean
        return check(root);
                    ^

Next step

Check your understanding

10 quick questions