Trees: nodes, depth, height and how they are stored

Video lessonComing soon

1 An org chart is a tree

Arrays and linked lists keep values in a line. A company does not work like that. The CEO has people who report to her, and they have reports of their own.

WebCTOiOSAppCEOCFOTax
A small company
1425869
The same chart, with numbers

An org chart is a tree. Each box is a node, and each line from a boss down to a report is an edge. Everyone except the CEO has exactly one boss.

In a binary tree, each node has at most two children: a left child and a right child. Nobody in this chart manages more than two people. This whole topic is about binary trees.

In code, a node holds a number, not a job title. The second drawing is the same chart with numbers, and the rest of the lesson uses it. The recursion tree from the recursion lessons was a tree too: each call was a node, and its calls were its children.

2 The words for a tree

Tree problems use a few words, all shown here on our tree:

One tree, every word
1425869
The root: 8 has no parent
  • Root. The top node, 8, with no parent. The program holds the tree through the root, as it held a list through its head.
  • Parent and child. 4 is the parent of 1 and 5, and they are its children. Every node except the root has one parent.
  • Siblings. Children of the same parent, such as 1 and 5.
  • Leaf. A node with no children: 1, 2 and 9. In the chart, a leaf has no reports.
  • Subtree. A node and everything below it. The subtree of 4 is the CTO's team: 4, 1, 5 and 2.
  • Edges. Each node except the root has one edge up to its parent, so n nodes have n − 1 edges.

Each child is the root of a smaller tree. So a question about a tree can be asked again of its two subtrees. That is why recursion fits trees so well.

3 Depth and height

Two numbers say where a node sits. In the chart, depth is how many bosses are above a person, and height is how many levels of reports are below.

  • Depth counts the edges from the root down to the node. The root has depth 0, and node 2 has depth 3.
  • Height counts the edges on the longest path from the node down to a leaf. A leaf has height 0, and node 4 has height 2, by 4 → 5 → 2.
1425869
The longest path from the root: 3 edges, so the tree has height 3
NodeDepthHeight
803
412
611
120
521
920
230

The nodes at one depth form a level: level 2 holds 1, 5 and 9. The tree's height is its root's height, 3. It equals the depth of the deepest node.

This lesson counts edges, but many problems count nodes. LeetCode's "maximum depth" counts the nodes on the longest path: 4 for our tree, and 0 for an empty tree. That is the height in edges plus 1. Before writing code, check which one the problem counts.

4 Shapes, and why height matters

The same number of nodes can make very different trees:

dbeafcg
Perfect
dbeafc
Complete
badce
Full
dcba
Skewed
  • Perfect. Every level is full.
  • Complete. Every level is full except maybe the last, which fills from the left.
  • Full. Every node has 0 or 2 children, never 1.
  • Skewed. Every node has one child, so the tree is a line, like a linked list.
  • Balanced. At every node, the heights of the two subtrees differ by at most 1. Our tree is balanced: at the root, they are 2 and 1.

Each level of a perfect tree holds twice as many nodes as the one above: 1, 2, 4, 8 and so on. So 17 levels hold more than 10⁵ nodes, and the height is about log₂ n. A skewed tree has one node per level.

Tree of 10⁵ nodesHeight
Balancedabout 17
Skewedabout 10⁵

A walk from the root to a leaf takes one step per level, and recursion goes one call deeper per level. So the height decides the cost. Problems rarely promise a balanced tree, so code must handle the skewed one.

5 A node with two pointers

A tree node is a linked list node with two next pointers. It holds a value, val, a pointer left to its left child, and a pointer right to its right child. A missing child is null, so a leaf has both pointers null. The function gets the root, and an empty tree is a null root.

On oneby7 and on LeetCode, every tree problem uses the same class, TreeNode. Here it is, with our tree built by hand. We build from the bottom up, so each child exists before its parent:

C++

Real addresses. left and right are pointers, and nullptr marks a missing child. root->left->right->left->val follows three pointers from 8 and reads 2.

References. left and right refer to the children, and null marks a missing child. root.left.right.left.val follows three references from 8 and reads 2.

References. left and right refer to the children, and None marks a missing child. root.left.right.left.val follows three references from 8 and reads 2.

References. left and right refer to the children, and null marks a missing child. root.left.right.left.val follows three references from 8 and reads 2.

Pointers. Left and Right hold the children's addresses, and nil marks a missing child. A field we leave out of &TreeNode{…} starts as nil.

Option<Rc<RefCell<TreeNode>>>. None is a missing child. Rc lets more than one variable hold the same node, and RefCell lets us change a node through it. The small helper node hides that wrapping while we build.

References. left and right refer to the children, and null marks a missing child. root.left.right.left.val follows three references from 8 and reads 2.

6 The array the problems give

Examples write a tree as one array: [8, 4, 6, 1, 5, null, 9, null, null, 2]. This is the level-order form. It lists the nodes level by level, left to right, with null for a missing child. The problem builds the nodes and passes our function the root.

To read an example, we rebuild the tree. The first value is the root. Then each node, in the order it was placed, takes the next two values as its left and right child. The nodes wait their turn in a queue:

Reading the array into a tree
8041621354null596null7null829
The array
8
8 is the root. Queue: 8

A null never joins the queue, so it takes no children. The nulls at the end are left out: 5's right child and the children of 9 and 2.

A complete tree has no gaps, so its array has no nulls. Then the index alone finds a node's family. The node at index i has its children at 2i + 1 and 2i + 2, and its parent at (i − 1) / 2, rounded down:

3751089
A complete tree
1007192335485
7 is at index 1. Its children are at 3 and 4

The heaps lesson stores a tree this way, with no pointers at all. It needs a complete tree. With gaps, every missing node needs an empty place, and a skewed tree of 30 nodes would need about 10⁹ places.

7 Height and size, by asking the children

The CEO wants to know how many people work for the company. She does not count them herself. She asks her two reports how many people are in their teams. They ask their own reports, all the way down. Someone with no reports answers 1. Each boss adds the two answers, adds 1 for herself, and passes the total up.

That is recursion on a tree. A subtree is a smaller tree, so the same function answers for it. A missing child is an empty tree, and it answers 0:

size(node) = 1 + size(left) + size(right)

The height works the same way, with max in place of +. Here we count nodes, as LeetCode's maxDepth does, so an empty tree is 0 and a leaf is 1:

maxDepth(node) = 1 + max(maxDepth(left), maxDepth(right))

In the steps, the second tree holds each node's answer. A ? marks a node still waiting for its children:

Answers travel up from the leaves
1425869
Leaves: 1 + max(0, 0) = 1
1?1???1
Answers

A node answers only after both its children have. The table lists the calls in the order they finish:

NodeleftDepthrightDepthmaxDepthsize
10011
20011
51022
41234
90011
60122
83247

The root's row comes last: depth 4, size 7. The 0s are the null children answering.

C++

Check before you follow. root->left on a null root is a Runtime Error, so the null check comes first.

Check before you follow. root.left on a null root throws a NullPointerException, so the null check comes first.

About 1,000 calls deep. By default, Python stops a recursion at about 1,000 nested calls with a RecursionError. A skewed tree goes far deeper. sys.setrecursionlimit raises the limit, or the iterative traversals lesson removes the recursion.

Check before you follow. root.left on a null root throws a TypeError, so the null check comes first.

Built-in max. Go 1.21 added max for numbers. On an older Go, compare the two depths with an if.

clone() copies the Rc, not the subtree. It makes one more handle to the same child, which the call then owns. let … else returns 0 when root is None, and borrow() reads the node inside the RefCell.

Check before you follow. root.left on a null root throws a NullReferenceException, so the null check comes first.

Cost. Each node is called once and does O(1) work, so both functions take O(n) time. The extra space is the call stack. It holds one call per node on the path from the root to the current node, so it is O(h) for a tree of height h. That is about 17 calls in a balanced tree of 10⁵ nodes, and 10⁵ in a skewed one.

The next subtopic opens with a lesson on what a recursive call should return, and goes deeper into this idea.

8 Mistakes, and what comes next

  • Counting edges when the problem counts nodes. If maxDepth returns 0 at a leaf, it counts edges, and our tree gives 3 instead of 4.
  • Following a null child. root.left.val with no left child is a Runtime Error. A base case that stops only at leaves still fails on node 6: it calls itself on 6's missing left child. A null check first covers every missing child.
  • Mixing up depth and height. Node 4 has depth 1 and height 2. Depth needs the path above, so it is passed down. Height needs the subtree, so it is returned up.
  • The empty tree. [] gives a null root, and the answer is 0. The null check handles it.
  • Deep recursion. A skewed tree of 10⁵ nodes makes 10⁵ nested calls. Deep recursion can overflow the call stack, and that is a Runtime Error. The iterative traversals lesson keeps its own stack instead.

Every problem in this topic hands us the root of a binary tree. The next lesson visits every node in a set order: preorder, inorder and postorder. Then come the same orders with an explicit stack, and later, level order with a queue.

Before writing a tree function, decide what it returns for a null child. That answer is the base case.

Practice it

Finished this lesson?

Mark it read and it is ticked on the roadmap and in the list.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.