Lesson 1 · Non-linear structures

Trees and Hierarchical Data

A tree stores data as a hierarchy: one root, every other node with exactly one parent, and no cycles. Most tree operations walk one path from the root, so the tree's height, not its size, sets the cost.

Trees and Hierarchical Data concept diagramA visual explanation of the layout and operations shown in this lesson.831016914start at the root, visit a child subtree, then return to the parent
1

Hierarchy Instead of Sequence

A tree data structure stores values in nodes joined by edges, arranged as parents and children. One node, the root, has no parent. Every other node has exactly one parent. There are no cycles, so there is exactly one path from the root to any node.

Counting follows from that: a tree with n nodes has n − 1 edges, one from each node up to its parent, and none from the root. Add one more edge and some node becomes reachable two ways, which is a cycle; the result is a general graph, not a tree. Remove any edge and the tree splits in two.

Trees fit data that is already a hierarchy: folders inside folders, HTML elements inside elements, an organisation chart, the parse tree of an expression. They are also built on purpose where the data has no hierarchy at all, because a well-shaped tree lets a search throw away half of what is left at each step.

  • One root, one parent for every other node, no cycles
  • n nodes, n − 1 edges, one path to each node
  • Used for real hierarchies and for fast search
2

Tree Terminology

Most exam questions on trees test the words, so they are worth getting exact. A leaf is a node with no children; an internal node has at least one. Siblings share a parent. The ancestors of a node are the nodes on its path up to the root; its descendants are every node below it.

The degree of a node is its number of children, and the degree of the tree is the largest of these, so a binary tree has degree 2. (In graph theory, degree also counts the edge to the parent; trees use the child count.)

A subtree is a node together with all its descendants, and it is a tree in its own right. That is why tree code is usually recursive: solve the problem for each child's subtree, then combine the answers at the parent. The order in which a recursive walk visits nodes is covered in tree traversals.

  • Root, parent, child, sibling, leaf, internal node
  • Degree of a node = number of children
  • Every subtree is a tree, so recursion fits
3

Height and Depth of a Tree

The height and depth of a tree are measured in opposite directions, and mixing them up is the most common mistake. Depth of a node is the number of edges from the root down to it, so the root has depth 0. Height of a node is the number of edges on the longest path from it down to a leaf, so every leaf has height 0. The height of the tree is the height of its root, which is also the largest depth of any node.

A level is all the nodes at one depth; level 0 is just the root.

Some textbooks count nodes instead of edges, which makes a single node height 1 instead of 0. Both are in use and they differ by exactly one, so say which one you mean. With edges, an empty tree has height −1.

  • Depth: edges from the root down to the node
  • Height: edges from the node down to its deepest leaf
  • Edge and node counting differ by one; state yours
Key reference

Terms, operations, and practical uses

Words for nodes

  • RootThe one node with no parent; every path starts here.
  • LeafA node with no children.
  • Internal nodeA node with at least one child.
  • SiblingsNodes with the same parent.
  • SubtreeA node and everything below it; itself a tree.

Measurements

  • DepthEdges from the root down to the node. The root has depth 0.
  • HeightEdges on the longest path from the node down to a leaf. A leaf has height 0.
  • LevelAll nodes at the same depth.
  • DegreeNumber of children of a node; for the tree, the largest such number.

Shapes

  • BalancedHeight kept at O(log n), so every path is short.
  • DegenerateEvery node has one child; height n − 1, as slow as a list.
  • n − 1 edgesAny tree with n nodes has exactly n − 1 edges; one more makes a cycle.
Implementation

Code in Python, C++ and Java

def inorder(node, answer):
    if node is None:
        return
    inorder(node.left, answer)
    answer.append(node.value)
    inorder(node.right, answer)


class Node:
    def __init__(self, value, left=None, right=None):
        self.value, self.left, self.right = value, left, right

root = Node(8, Node(3, Node(1), Node(6)), Node(10))
result = []
inorder(root, result)
print(*result)
#include <iostream>
#include <vector>
using namespace std;

struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int v, TreeNode* l = nullptr, TreeNode* r = nullptr) : val(v), left(l), right(r) {}
};

void inorder(TreeNode* node, vector<int>& answer) {
    if (node == nullptr) return;
    inorder(node->left, answer);
    answer.push_back(node->val);
    inorder(node->right, answer);
}

int main() {
    TreeNode* root = new TreeNode(8, new TreeNode(3, new TreeNode(1), new TreeNode(6)), new TreeNode(10));
    vector<int> answer;
    inorder(root, answer);
    for(size_t i = 0; i < answer.size(); i++) {
      if (i) cout << ' ';
      cout << answer[i];
    }
    cout << '\n';
}
import java.util.*;

public class Main {
    static class TreeNode {
        int val;
        TreeNode left, right;
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) { this.val = val; this.left = left; this.right = right; }
    }

    void inorder(TreeNode node, List<Integer> answer) {
        if (node == null) return;
        inorder(node.left, answer);
        answer.add(node.val);
        inorder(node.right, answer);
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(8, new TreeNode(3, new TreeNode(1), new TreeNode(6)), new TreeNode(10));
        List<Integer> answer = new ArrayList<>();
        new Main().inorder(root, answer);
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < answer.size(); i++) {
          if (i > 0) sb.append(' ');
          sb.append(answer.get(i));
        }
        System.out.println(sb);
    }
}
Watch it run

Step through it

Running on keys 1 to 7, inserted as 4 2 6 1 3 5 7 and as 1 2 3 4 5 6 7

order: 4 2 6 1 3 5 74root26each new key walks down from the root to an empty spot
Step 1

Insert 4, 2, 6

We build a binary search tree: smaller keys go left, larger go right. 4 arrives first and becomes the root, the one node with no parent. 2 is smaller, so it becomes 4's left child; 6 is larger, so it becomes the right child. 2 and 6 are siblings: same parent.

Output
1 / 11
4

Why Shape Decides the Cost

Search, insert and delete in most trees walk one path from the root down, so their cost is the height, not the number of nodes. A tree of n nodes can have any height from ⌊log₂ n⌋, when every level is full, to n − 1, when every node has one child.

That worst shape is a degenerate tree: a linked list drawn as a tree. It is not rare. Insert keys in sorted order into a plain binary search tree and every key goes to the right of the last one, which builds exactly this chain. The code is correct and small tests pass, but at a million keys a search takes a million steps instead of twenty, and recursive code needs a million stack frames.

A balanced tree keeps its height at O(log n). AVL and red-black trees do it by rotating nodes after each insert or delete; B-trees do it by splitting full nodes.

Height and cost by shape
ShapeHeightSearch, insert, delete
Full levels (perfect or complete)⌊log₂ n⌋O(log n)
Self-balancing (AVL, red-black)under 1.44 log₂ n (AVL), 2 log₂ n (red-black)O(log n) guaranteed
Plain BST, random insert orderabout 3 log₂ n on averageO(log n) expected
Degenerate (sorted inserts)n − 1O(n)
  • Cost follows height, not size
  • Sorted input builds a chain in a plain BST
  • Balancing keeps height at O(log n)
5

Types of Trees

The types of trees differ in how many children a node may have and what order they keep. Each one exists to make one kind of question cheap.

A general (n-ary) tree lets a node have any number of children, as in a file system. A binary tree allows at most two, left and right, and its own lesson covers full, complete and perfect binary trees. A binary search tree adds an order: smaller keys on the left, larger on the right, so search can discard a whole subtree at each step and an in-order walk gives the keys sorted.

AVL trees and red-black trees are binary search trees that keep themselves balanced. B-trees give each node many keys and children, so the tree is only a few levels deep; that suits disks, where each level is one read, which is why databases use them. Heaps order by priority instead of by key and keep the smallest or largest at the root. Tries store strings by prefix, one character per edge. Segment trees and Fenwick trees store sums or minimums over ranges.

Which tree answers which question
TreeRuleGood at
General (n-ary)Any number of childrenReal hierarchies
Binary search treeLeft < node < rightOrdered search, sorted output
AVL, red-blackBST + balance ruleGuaranteed O(log n)
B-tree, B+ treeMany keys per nodeDisk-based indexes
HeapParent beats childrenFast min or max
TrieOne character per edgePrefix lookup
Segment, FenwickNode stores a range totalRange queries with updates
  • Pick the tree by the query it must answer
  • Ordered keys: BST, kept balanced by AVL or red-black
  • Disk: B-tree; priority: heap; prefixes: trie; ranges: segment or Fenwick