AlgoTales · Roadmap

Tree terminology

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

Where you will meet this in real life

A tree is a set of boxes joined by lines with one box at the top, called the root. Each box can have children below it. Words like parent, child, leaf, and level are simply the language everyone uses to talk about such structures.

Practical use cases

  • Web app: Reading a web page as a tree. Every HTML page is a tree: the html tag is the root, body is its child, and the divs and paragraphs hang below. When a developer writes "find the parent of this button" in jQuery or React, they use tree words. Knowing them makes DOM code much easier to follow.
  • Web app: Category and menu structure. An online store has Electronics, with Phones and Laptops under it, and Phones has Android and iPhone. Each category is a node, and a product page breadcrumb simply walks from a leaf back up to the root.
  • System: Folders and company org charts. Your computer folders form a tree, with one top drive and folders inside folders. Org charts, comment threads with replies and file explorers are all the same shape and use the same vocabulary. Because all of these share one shape, an idea learned for folders, such as walking down through children, works unchanged on menus, replies and chart hierarchies.

The story: The Wedding Family Tree

Grandpa Bhaskar was turning eighty, and the whole family was gathering for a big celebration. Mira's job was to draw the family chart on a chart paper so that guests could find their seats. She started with Grandpa at the top, drew lines down to his two children, and lines down from them to the grandchildren.

The guests kept asking confusing questions. "Who is my parent on this chart?" "Who are my brothers and sisters?" "Who stands at the very bottom with nobody under them?" Mira realised that without names for each position, nobody could talk about the chart. So she wrote little labels on it.

Grandpa at the top: the root. The person directly above you: your parent. People directly below: your children. People who share your parent: siblings. People with nobody below: leaves. Everyone from you up to Grandpa: your ancestors.

Kabir laughed: "It is an upside-down tree, with the root on top!" Mira nodded. "Yes, and these names are the language every computer scientist speaks. Once you know them, every tree lesson becomes easy to follow."

How to spot this problem, and where you need it

You have data where things contain other things, such as folders, menus, replies or categories, and you struggle to describe or store it clearly.

Signs you need it

  • One item has many children but each child has only one parent, like categories, comment replies or folders.
  • You find yourself drawing boxes and arrows, or storing a parent_id column in a table.
  • Developers talk about "root", "leaf", "parent", "sibling" or "depth" and you need to follow the conversation.

Where to use it in a project

  • Designing nested menus, category pages, comment threads and permission hierarchies.
  • Working with the DOM in the browser, folder listings in file uploads and JSON documents.

The solution

Learn the handful of words and use them. The root is the top box. A parent has children below it, and children of the same parent are siblings. A leaf has no children. Depth is how many steps down from the root, and height is how far the deepest leaf is below. Once you can name the parts, you can choose how to store and walk through the tree.

Payoff: Before: confused talks about "the thing above the thing". After: one clear word per idea, so designs and code reviews go faster.

Explain it like I am 8

Think of a family chart. Grandpa is at the top. His kids hang below him, and their kids hang below them. A tree in computers is just that chart: boxes joined by lines, with one boss box at the top and nobody ever pointing back upwards.

How it works, step by step

  1. Root: the one node at the top, with no parent.
  2. Parent and child: two nodes joined by an edge; the upper one is the parent, the lower one is the child. Children of the same parent are siblings.
  3. Leaf: a node with no children. A node that has at least one child is an internal node.
  4. Depth of a node = steps from the root down to it. Height of the tree = the deepest leaf's depth.
  5. Binary tree: every node has at most two children, named left and right. A subtree is any node plus everything below it.

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

// Walk the tree once and record the vocabulary for every node.
function describe(?TreeNode $n, ?TreeNode $parent, int $depth, array &$info): void {
    if ($n === null) return;
    $info[$n->val] = [
        'parent' => $parent === null ? 'none (root)' : $parent->val,
        'depth'  => $depth,
        'leaf'   => $n->left === null && $n->right === null,
    ];
    describe($n->left, $n, $depth + 1, $info);
    describe($n->right, $n, $depth + 1, $info);
}

$info = [];
describe(sampleTree(), null, 0, $info);
foreach ($info as $val => $i) {
    echo "Node $val: parent=" . $i['parent'] . ", depth=" . $i['depth'] . ", " . ($i['leaf'] ? 'leaf' : 'internal') . PHP_EOL;
}

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

// Walk the tree once and record the vocabulary for every node.
function describe(n, parent, depth, info) {
  if (n === null) return;
  info[n.val] = {
    parent: parent === null ? 'none (root)' : parent.val,
    depth: depth,
    leaf: n.left === null && n.right === null,
  };
  describe(n.left, n, depth + 1, info);
  describe(n.right, n, depth + 1, info);
}

const info = {};
describe(sampleTree(), null, 0, info);
for (const val in info) {
  const i = info[val];
  console.log('Node ' + val + ': parent=' + i.parent + ', depth=' + i.depth + ', ' + (i.leaf ? 'leaf' : 'internal'));
}

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

    // Everything we know about one node.
    record Info(String parent, int depth, boolean leaf) {}

    // Walk the tree once and record the vocabulary for every node.
    static void describe(TreeNode n, TreeNode parent, int depth, Map<Integer, Info> info) {
        if (n == null) return;
        info.put(n.val, new Info(parent == null ? "none (root)" : String.valueOf(parent.val),
                                 depth, n.left == null && n.right == null));
        describe(n.left, n, depth + 1, info);
        describe(n.right, n, depth + 1, info);
    }

    public static void main(String[] args) {
        Map<Integer, Info> info = new TreeMap<>();   // TreeMap keeps the nodes sorted by value
        describe(sampleTree(), null, 0, info);
        for (var entry : info.entrySet()) {
            Info i = entry.getValue();
            System.out.println("Node " + entry.getKey() + ": parent=" + i.parent() + ", depth=" + i.depth()
                    + ", " + (i.leaf() ? "leaf" : "internal"));
        }
    }
}

Go

package main

import (
	"fmt"
	"sort"
	"strconv"
)

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
}

// Everything we know about one node.
type Info struct {
	parent string
	depth  int
	leaf   bool
}

// describe walks the tree once and records the vocabulary for every node.
func describe(n, parent *TreeNode, depth int, info map[int]Info) {
	if n == nil {
		return
	}
	p := "none (root)"
	if parent != nil {
		p = strconv.Itoa(parent.Val)
	}
	info[n.Val] = Info{parent: p, depth: depth, leaf: n.Left == nil && n.Right == nil}
	describe(n.Left, n, depth+1, info)
	describe(n.Right, n, depth+1, info)
}

func main() {
	info := map[int]Info{}
	describe(sampleTree(), nil, 0, info)
	vals := []int{}
	for v := range info {
		vals = append(vals, v)
	}
	sort.Ints(vals) // map order is random in Go, so print in value order
	for _, v := range vals {
		i := info[v]
		kind := "internal"
		if i.leaf {
			kind = "leaf"
		}
		fmt.Printf("Node %d: parent=%s, depth=%d, %s\n", v, i.parent, i.depth, kind)
	}
}

Time: O(n) · Extra space: O(h). Visiting every node once is O(n); the recursion remembers one path at a time, as deep as the tree is tall (h).

Watch out for

  • Mixing up depth (counted from the root down to a node) and height (counted from a node down to its deepest leaf).
  • Thinking a binary tree must have exactly two children everywhere. At most two: a node can have one child or none.
  • Forgetting that a tree has one root and no loops. A child never points back up to an ancestor.

Quick check

  1. In our example tree, which nodes are leaves?
    • 4, 7 and 6
    • 2, 5, 3
    • Only 7
    • 1, 2, 3
  2. What do we call two nodes that share the same parent?
    • Ancestors
    • Descendants
    • Siblings
  3. What is the depth of node 7 (steps from the root)?
    • 2
    • 3
    • 4