Kodewick
Start learning →
Binary trees and recursion22 / 52

Binary trees and recursion

Lesson 22 of 52 · Part 5 · Trees · about 20 minutes

A binary tree gives each node at most two children, and each side is a smaller binary tree, so tree code is nearly always recursive: an empty tree gives 0, otherwise combine both subtrees, as in count(t->left) + count(t->right) + 1.

Folders inside folders, a tournament bracket, the expression (3 + 4) * 5: each is one thing with a few things of the same shape hanging under it. That shape is a tree. When every node has at most two below it, it is a binary tree, the most central structure in a data structures course.

A node: one value, two pointers

Next to a linked-list node, a binary tree node just swaps the one next for left and right. Where there is no child, the pointer is nullptr. The constructor gives both pointers defaults, so new TreeNode(4) is a leaf.

1struct TreeNode {2    int val;3    TreeNode *left, *right;4    TreeNode(int v, TreeNode* l = nullptr, TreeNode* r = nullptr)5        : val(v), left(l), right(r) {}6};

The node at the top is the root; a node with no children is a leaf; counting down from the root, which is level 1, the number of levels is the tree's height.

1
2
4
5
3
6

A binary tree of 6 nodes: the root is 1, the leaves are 4, 5 and 6, the height is 3. 3 has no left child, so 6 is drawn on the right

This is where the recursion comes from: the left and right subtrees are binary trees too, and smaller ones. So anything you ask about a tree, you can first ask its two subtrees and then combine their answers; an empty subtree (nullptr) answers straight away.

Choose one

What is the height of this tree, and how many leaves does it have?

1        A2       / \3      B   C4     / \   \5    D   E   F6       /7      G
Fill inTap one to fill a blank; tap a blank to take it back

Pick one for the blank so the program prints 1 2 1: the root is 1, its left child is 2, and there is no right child.

1#include <iostream>2using namespace std;3 4struct TreeNode {5    int val;6    TreeNode *left, *right;7    TreeNode(int v, TreeNode* l = nullptr, TreeNode* r = nullptr)8        : val(v), left(l), right(r) {}9};10 11int main() {12    TreeNode* t =  TreeNode(1, new TreeNode(2));13    cout << t->val << " " << t->left->val << " " << (t->right == nullptr) << "\n";14    return 0;15}

Counting nodes and height, recursively

Nodes = the left subtree's nodes + the right subtree's nodes + 1 (this one). Height = the taller of the two subtrees + 1. An empty tree has 0 nodes and height 0.

main.cpp
1#include <iostream>2#include <algorithm>3using namespace std;4 5struct TreeNode {6    int val;7    TreeNode *left, *right;8    TreeNode(int v, TreeNode* l = nullptr, TreeNode* r = nullptr)9        : val(v), left(l), right(r) {}10};11 12int count(TreeNode* t) {13    if (t == nullptr) return 0;14    return count(t->left) + count(t->right) + 1;15}16 17int height(TreeNode* t) {18    if (t == nullptr) return 0;19    int l = height(t->left);20    int r = height(t->right);21    return max(l, r) + 1;22}23 24void destroy(TreeNode* t) {         // delete both children first, then this node25    if (t == nullptr) return;26    destroy(t->left);27    destroy(t->right);28    delete t;29}30 31int main() {32    // the tree from the first picture: 2 and 3 under 1, 4 and 5 under 2, 6 to the right of 333    TreeNode* t = new TreeNode(1, new TreeNode(2, new TreeNode(4), new TreeNode(5)),34                                  new TreeNode(3, nullptr, new TreeNode(6)));35    cout << "nodes " << count(t) << ", height " << height(t) << endl;36    destroy(t);37    return 0;38}
Output
nodes 6, height 3

Every node came from new, so it has to be deleted when you are done. destroy is recursive too: first clear out both subtrees, then delete this node; delete this node first and t->left is gone. Later examples sometimes skip this step to stay short; real programs shouldn't.

Press "Visualize" to watch the calls to count pile up on the stack: at each node it asks two more times further down, and only at nullptr do the returns begin.

h(1)
1int height(TreeNode* t) {2    if (t == nullptr) return 0;3    int l = height(t->left);4    int r = height(t->right);5    return max(l, r) + 1;6}

The recursion tree of height(1): it asks all the way down to the leaves, and the answers come back up level by level

Every recursion that "asks the whole tree" looks like this: each node is visited once, O(n); the recursion is as deep as the tree is tall, which at worst (a tree grown into a chain) is O(n).

Guess the outputA wrong guess is fine

This is the tree from the first picture: the root is 1, the leaves are 4, 5 and 6. What does f work out, and what does it print?

1#include <iostream>2using namespace std;3 4struct TreeNode {5    int val;6    TreeNode *left, *right;7    TreeNode(int v, TreeNode* l = nullptr, TreeNode* r = nullptr)8        : val(v), left(l), right(r) {}9};10 11int f(TreeNode* t) {12    if (t == nullptr) return 0;13    if (t->left == nullptr && t->right == nullptr) return t->val;14    return f(t->left) + f(t->right);15}16 17int main() {18    TreeNode* t = new TreeNode(1, new TreeNode(2, new TreeNode(4), new TreeNode(5)),19                                  new TreeNode(3, nullptr, new TreeNode(6)));20    cout << f(t) << endl;21    return 0;22}
Change it

This count gets the empty tree wrong and prints 13 instead of 6. Change only the number in the green box so it counts correctly.

1#include <iostream>2using namespace std;3 4struct TreeNode {5    int val;6    TreeNode *left, *right;7    TreeNode(int v, TreeNode* l = nullptr, TreeNode* r = nullptr)8        : val(v), left(l), right(r) {}9};10 11int count(TreeNode* t) {12    if (t == nullptr) return ;13    return count(t->left) + count(t->right) + 1;14}15 16int main() {17    TreeNode* t = new TreeNode(1, new TreeNode(2, new TreeNode(4), new TreeNode(5)),18                                  new TreeNode(3, nullptr, new TreeNode(6)));19    cout << count(t) << "\n";20    return 0;21}
Should print
6
Put in orderDrag, or use the arrows

Put the three lines of height in order: deal with the empty tree, then ask the two subtrees, then work out this node's answer. The tree is the one from the first picture, so the program should print 3.

  1. return max(l, r) + 1;
  2. int l = height(t->left), r = height(t->right);
  3. if (t == nullptr) return 0;
Should print
3
Choose one

While height recurses, what decides the largest number of calls stacked up at the same time?

Exercise 1

Count the leaves

Finish leaves so it returns how many leaves there are.

It should print
4
exercise1.cpp
1#include <iostream>2using namespace std;3 4struct TreeNode {5    int val;6    TreeNode *left, *right;7    TreeNode(int v, TreeNode* l = nullptr, TreeNode* r = nullptr)8        : val(v), left(l), right(r) {}9};10 11int leaves(TreeNode* t) {12    // empty tree: 0; a leaf: 1; otherwise add the left and right13    return 0;14}15 16int main() {17    TreeNode* t = new TreeNode(8, new TreeNode(3, new TreeNode(1), new TreeNode(6, new TreeNode(4), new TreeNode(7))),18                                  new TreeNode(10, nullptr, new TreeNode(14)));19    cout << leaves(t) << endl;20    return 0;21}
Output
Press Run or Ctrl+Enter
Exercise 2

The largest value

Finish max_val: return the largest value in the whole tree (the tree is not empty).

It should print
20
exercise2.cpp
1#include <iostream>2#include <algorithm>3using namespace std;4 5struct TreeNode {6    int val;7    TreeNode *left, *right;8    TreeNode(int v, TreeNode* l = nullptr, TreeNode* r = nullptr)9        : val(v), left(l), right(r) {}10};11 12int max_val(TreeNode* t) {13    // assume this node is the largest; if a subtree isn't empty, ask it and compare14    return t->val;15}16 17int main() {18    TreeNode* t = new TreeNode(5, new TreeNode(12, new TreeNode(3)),19                                  new TreeNode(7, new TreeNode(20), new TreeNode(1)));20    cout << max_val(t) << endl;21    return 0;22}
Output
Press Run or Ctrl+Enter

The properties exams use

NameWhat it isNodes
Full binary treeEvery level filledExactly 2ʰ − 1 at height h
Complete binary treeEvery level filled except the last, which fills from the left with no gapsHeight ⌊log₂ n⌋ + 1 with n nodes

And one that comes up almost every year: the number of leaves n₀ = the number of nodes with two children n₂ + 1. Count them in the tree from the first picture: 1 and 2 have two children (n₂ = 2), and the leaves are 4, 5 and 6 (n₀ = 3): exactly one more.

1
2
4
5
3
6

Counting the tree from the first picture: n₂ = 2, n₁ = 1, n₀ = 3 = n₂ + 1

Why: every node except the root has one edge above it, so edges = n − 1; edges also equal n₁ + 2n₂ (one from each node with one child, two from each with two). Put in n = n₀ + n₁ + n₂ and you get n₀ = n₂ + 1.

In exams: "a binary tree has 10 leaves; how many nodes have degree 2?": 9. "A complete binary tree has 1000 nodes; how tall is it?": ⌊log₂ 1000⌋ + 1 = 10. A complete binary tree is also the shape of the heap, later in this chapter.

Choose one

A binary tree has 15 leaves and 10 nodes with exactly one child. How many nodes does it have in all?

Choose one

A complete binary tree has 100 nodes. What is its height?

Choose one

A full binary tree has height 5. How many nodes and how many leaves does it have?

With the STL

The STL has no "binary tree" container: a structure like TreeNode is always one you write yourself. But several containers are trees inside; they just don't let you touch the nodes:

ContainerThe tree insideWhat the main operations cost
set / map / multiset / multimapA red-black tree (a binary search tree that keeps itself balanced)Insert, find, erase O(log n)
priority_queueA complete binary tree (a heap), stored level by level in a vectorpush / pop O(log n), top O(1)

A complete binary tree fills level by level with no gaps, so it needs no pointers at all: put the values into a vector level by level, and index i has its left child at 2i + 1, its right child at 2i + 2 and its parent at (i − 1) / 2.

main.cpp
1#include <iostream>2#include <vector>3#include <algorithm>4using namespace std;5 6// a complete binary tree stored level by level in a vector: index i has children 2i+1 and 2i+27int height(const vector<int>& a, int i) {8    if (i >= (int)a.size()) return 0;9    return max(height(a, 2 * i + 1), height(a, 2 * i + 2)) + 1;10}11 12int main() {13    vector<int> a = {1, 2, 3, 4, 5, 6};14    int n = a.size();15    for (int i = 0; i < n; i++) {16        if (2 * i + 1 >= n) break;          // the rest are leaves17        cout << a[i] << "'s children: " << a[2 * i + 1];18        if (2 * i + 2 < n) cout << " " << a[2 * i + 2];19        cout << endl;20    }21    cout << "height " << height(a, 0) << endl;22    return 0;23}
Output
1's children: 2 3
2's children: 4 5
3's children: 6
height 3

Note this tree is not the one from the first level: filled level by level, 6 is 3's left child. A tree like that first one, where 3 has only a right child, needs empty cells left for the gaps in an array, and a slanting chain needs about 2ⁿ cells, so general trees still use pointers. The heap later in this chapter is written on exactly this vector.

In interviews: LeetCode's TreeNode is nearly the same as the one in this lesson (plus a constructor with no arguments), and your function gets the root pointer TreeNode* root, with nullptr for an empty tree. Write "what an empty tree returns" first, then "how the left and right answers combine", and most tree problems are half done.

Choose one

A complete binary tree is stored level by level in a vector; index i has children 2i + 1 and 2i + 2. Which index is the parent of index 4?

Summary

Take-away

Binary trees: each side a smaller tree

  • A node: val + left + right, nullptr where there is no child; what you new, you delete
  • Every tree question asks the two subtrees first, then combines; an empty tree answers at once
  • Each node visited once is O(n); recursion depth = height
  • n₀ = n₂ + 1; a full tree has 2ʰ − 1 nodes; a complete tree fits in a vector
1int count(TreeNode* t) {2    if (t == nullptr) return 0;3    return count(t->left) + count(t->right) + 1;4}