AlgoTales · Roadmap

Height/depth

Beginner · 8 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Depth tells you how many steps down a node is from the root, and height tells you how far the deepest leaf is below a node. They measure how tall a tree is, which controls how many steps any search or update will need.

Practical use cases

  • Web app: Why one folder structure feels slow. A file manager in a web app stores folders 30 levels deep for one customer. Loading a path means walking through 30 parents, and breadcrumbs become unwieldy. Measuring depth lets the team put a limit on it and keep pages quick.
  • Web app: Nested comments depth limit. A forum allows replies to replies endlessly, and some threads reach 50 levels, which breaks the mobile layout. By checking depth, the site stops showing a Reply button after level 5 and flattens the rest. The forum stays readable on a phone.
  • System: Game AI and search trees. Chess and tic-tac-toe programs think ahead through a tree of moves. The height is how many moves ahead the program looks, and each extra level multiplies the work, so engines cap it. A program that looks 4 moves ahead is fast, while one that looks 12 moves ahead may take minutes, so developers choose the height carefully.

The story: Mira Measures the Mango Tree

In Grandpa Bhaskar's garden stood an old mango tree, and Kabir bet Mira a plate of aam papad that she could not measure how tall it was without climbing. Mira grinned and borrowed a diagram of the tree's branches from her science book: one trunk, splitting into branches, splitting into twigs.

"Easy," said Mira. "Stand at the tip of any twig. Count how many branch-joints you must pass to get down to the trunk. That count is the twig's depth." Kabir nodded. "And the tree's height?" "The longest such climb, from the trunk to the farthest twig."

But Kabir was sneaky: "What if I only ask about one branch? How tall is the part of the tree above that branch?" Mira thought, and found a lovely trick: ask each of the two sub-branches how tall they are, take the taller answer, and add one for the step you are standing on. A bare twig answers "zero".

That is how height is calculated in every tree: ask the children, take the bigger answer, add one. Mira collected her aam papad. Kabir noted that "depth looks up to the root; height looks down to the leaves".

How to spot this problem, and where you need it

A tree-shaped feature gets slower or messier as it nests deeper, and you need a number that tells you how deep or tall the structure has really become.

Signs you need it

  • Searches, breadcrumbs or folder loads take noticeably longer for some branches than others.
  • Users create endless nesting, such as comment replies or categories inside categories, that breaks the layout.
  • The problem says "maximum depth", "height of tree", "level of node" or "is it balanced".

Where to use it in a project

  • Setting limits on nesting levels for comments, menus, categories and folders.
  • Checking whether a search tree has become too tall and needs rebalancing.

The solution

For depth, count steps from the root down to the node. For height, ask each child for its own height, take the larger answer and add one for the current node; a missing child counts as zero. This is a small recursive function that visits each node once. Store or check the result, then enforce limits or rebalance when the height grows too large.

Payoff: Before: a 50-level comment thread broke the page. After: a depth check caps it at 5 levels and the layout stays tidy.

Explain it like I am 8

Depth is "how many steps down from the top am I?". Height is "how many steps down is the farthest leaf below me?". For height, you ask each child how tall it is, take the larger answer, and add one more step for yourself.

How it works, step by step

  1. Depth of a node: start at the root (depth 0) and add one for each edge you walk down.
  2. Height of a node: the number of edges on the longest path from it down to a leaf.
  3. Base case: an empty spot (null) has height -1, so a leaf (two empty children) works out to 0.
  4. Recurse: height(node) = 1 + max(height(left), height(right)). Children are measured first, then the parent.
  5. The height of the tree is the height of the root, and it also equals the deepest leaf's depth.

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;
}

// Height: edges on the longest walk down to a leaf (null = -1, so a leaf = 0).
function height(?TreeNode $n): int {
    if ($n === null) return -1;
    return 1 + max(height($n->left), height($n->right));
}

// Depth of a target value: steps from the root, or -1 if it is not in the tree.
function depthOf(?TreeNode $n, int $target, int $depth = 0): int {
    if ($n === null) return -1;
    if ($n->val === $target) return $depth;
    $found = depthOf($n->left, $target, $depth + 1);
    if ($found !== -1) return $found;
    return depthOf($n->right, $target, $depth + 1);
}

$root = sampleTree();
echo 'Height of the tree: ' . height($root) . PHP_EOL;          // 3
echo 'Height of node 2:   ' . height($root->left) . PHP_EOL;    // 2
echo 'Depth of node 7:    ' . depthOf($root, 7) . PHP_EOL;      // 3
echo 'Depth of node 99:   ' . depthOf($root, 99) . PHP_EOL;     // -1

JavaScript

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;
}

// Height: edges on the longest walk down to a leaf (null = -1, so a leaf = 0).
function height(n) {
  if (n === null) return -1;
  return 1 + Math.max(height(n.left), height(n.right));
}

// Depth of a target value: steps from the root, or -1 if it is not in the tree.
function depthOf(n, target, depth = 0) {
  if (n === null) return -1;
  if (n.val === target) return depth;
  const found = depthOf(n.left, target, depth + 1);
  if (found !== -1) return found;
  return depthOf(n.right, target, depth + 1);
}

const root = sampleTree();
console.log('Height of the tree: ' + height(root));        // 3
console.log('Height of node 2:   ' + height(root.left));   // 2
console.log('Depth of node 7:    ' + depthOf(root, 7));    // 3
console.log('Depth of node 99:   ' + depthOf(root, 99));   // -1

Java

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;
    }

    // Height: edges on the longest walk down to a leaf (null = -1, so a leaf = 0).
    static int height(TreeNode n) {
        if (n == null) return -1;
        return 1 + Math.max(height(n.left), height(n.right));
    }

    // Depth of a target value: steps from the root, or -1 if it is not in the tree.
    static int depthOf(TreeNode n, int target, int depth) {
        if (n == null) return -1;
        if (n.val == target) return depth;
        int found = depthOf(n.left, target, depth + 1);
        if (found != -1) return found;
        return depthOf(n.right, target, depth + 1);
    }

    public static void main(String[] args) {
        TreeNode root = sampleTree();
        System.out.println("Height of the tree: " + height(root));         // 3
        System.out.println("Height of node 2:   " + height(root.left));    // 2
        System.out.println("Depth of node 7:    " + depthOf(root, 7, 0));  // 3
        System.out.println("Depth of node 99:   " + depthOf(root, 99, 0)); // -1
    }
}

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
}

// height counts the edges on the longest walk down to a leaf (nil = -1, so a leaf = 0).
func height(n *TreeNode) int {
	if n == nil {
		return -1
	}
	return 1 + max(height(n.Left), height(n.Right))
}

// depthOf returns the steps from the root to target, or -1 if it is not in the tree.
func depthOf(n *TreeNode, target, depth int) int {
	if n == nil {
		return -1
	}
	if n.Val == target {
		return depth
	}
	if found := depthOf(n.Left, target, depth+1); found != -1 {
		return found
	}
	return depthOf(n.Right, target, depth+1)
}

func main() {
	root := sampleTree()
	fmt.Println("Height of the tree:", height(root))         // 3
	fmt.Println("Height of node 2:  ", height(root.Left))    // 2
	fmt.Println("Depth of node 7:   ", depthOf(root, 7, 0))  // 3
	fmt.Println("Depth of node 99:  ", depthOf(root, 99, 0)) // -1
}

Time: O(n) · Extra space: O(h). Every node is asked once. The call stack grows as deep as the tree is tall (h), which can be as bad as n for a long chain.

Watch out for

  • Mixing up depth and height. Depth counts from the root down to me; height counts from me down to my deepest leaf.
  • Being inconsistent about counting nodes vs edges. A single node has height 0 in edges, or 1 if you count nodes. Pick one and say which.
  • Forgetting the null base case, which makes the recursion run off the bottom of the tree and crash.

Quick check

  1. What is the height of a leaf (counting edges)?
    • -1
    • 1
    • 0
  2. How is a node&#39;s height worked out?
    • Add both children&#39;s heights
    • 1 + the bigger of the two children&#39;s heights
    • Count the nodes on its left side
  3. In the example tree, what is the depth of node 6?
    • 0
    • 1
    • 2
    • 3