Kodewick
Start learning →
Binary trees and recursion20 / 50

Binary trees and recursion

Lesson 20 of 50 · Part 5 · Trees · about 15 minutes

A binary tree is made of nodes with at most two children, and each side is a smaller binary tree, so tree code is usually recursive: count(t->left) + count(t->right) + 1 counts the nodes, with an empty tree giving 0.

Folders inside folders, a tournament bracket, an expression like (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, it's a binary tree, the most important kind in any 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 a left and a right. Where there is no child, the pointer is NULL.

1typedef struct Node {2    int val;3    struct Node *left, *right;4} Node;

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

That is where the recursion comes from: the left and right subtrees are binary trees themselves, and smaller ones. So any question about a tree can be asked of its two subtrees first, then the answers combined; an empty subtree (NULL) answers at once.

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 what goes in the blank so the program compiles and prints 1 2.

1#include <stdio.h>2#include <stdlib.h>3 4typedef struct Node {5    int val;6     *left, *right;7} Node;8 9int main(void) {10    Node leaf = {2, NULL, NULL};11    Node root = {1, &leaf, NULL};12    printf("%d %d\n", root.val, root.left->val);13    return 0;14}

Counting nodes and height, recursively

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

main.c
1#include <stdio.h>2#include <stdlib.h>3 4typedef struct Node {5    int val;6    struct Node *left, *right;7} Node;8 9Node *node(int v, Node *l, Node *r) {10    Node *n = malloc(sizeof(Node));11    n->val = v;12    n->left = l;13    n->right = r;14    return n;15}16 17int count(Node *t) {18    if (t == NULL) return 0;19    return count(t->left) + count(t->right) + 1;20}21 22int height(Node *t) {23    if (t == NULL) return 0;24    int l = height(t->left), r = height(t->right);25    return (l > r ? l : r) + 1;26}27 28int main(void) {29    // the tree from the first picture: 2 and 3 under 1, 4 and 5 under 2, 6 to the right of 330    Node *t = node(1, node(2, node(4, NULL, NULL), node(5, NULL, NULL)),31                      node(3, NULL, node(6, NULL, NULL)));32    printf("%d nodes, height %d\n", count(t), height(t));33    return 0;34}
Output
6 nodes, height 3

Press Visualize to watch the calls to count pile up on the stack: at every node it asks twice more, and only when it reaches NULL do the answers start coming back.

h(1)
h(2)
h(4)
h(5)
h(3)
h(6)

How height(1) is worked out: 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 visited once, O(n); the recursion is as deep as the tree is tall, O(n) at worst (when the tree is one long chain).

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 <stdio.h>2#include <stdlib.h>3 4typedef struct Node {5    int val;6    struct Node *left, *right;7} Node;8 9Node *node(int v, Node *l, Node *r) {10    Node *n = malloc(sizeof(Node));11    n->val = v; n->left = l; n->right = r;12    return n;13}14 15int f(Node *t) {16    if (t == NULL) return 0;17    if (t->left == NULL && t->right == NULL) return t->val;18    return f(t->left) + f(t->right);19}20 21int main(void) {22    Node *t = node(1, node(2, node(4, NULL, NULL), node(5, NULL, NULL)),23                      node(3, NULL, node(6, NULL, NULL)));24    printf("%d\n", f(t));25    return 0;26}
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 <stdio.h>2#include <stdlib.h>3 4typedef struct Node {5    int val;6    struct Node *left, *right;7} Node;8 9Node *node(int v, Node *l, Node *r) {10    Node *n = malloc(sizeof(Node));11    n->val = v; n->left = l; n->right = r;12    return n;13}14 15int count(Node *t) {16    if (t == NULL) return ;17    return count(t->left) + count(t->right) + 1;18}19 20int main(void) {21    Node *t = node(1, node(2, node(4, NULL, NULL), node(5, NULL, NULL)),22                      node(3, NULL, node(6, NULL, NULL)));23    printf("%d\n", count(t));24    return 0;25}
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 (l > r ? l : r) + 1;
  2. int l = height(t->left), r = height(t->right);
  3. if (t == NULL) 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, returning how many leaves there are.

It should print
4
exercise1.c
1#include <stdio.h>2#include <stdlib.h>3 4typedef struct Node {5    int val;6    struct Node *left, *right;7} Node;8 9Node *node(int v, Node *l, Node *r) {10    Node *n = malloc(sizeof(Node));11    n->val = v; n->left = l; n->right = r;12    return n;13}14 15int leaves(Node *t) {16    // empty: 0; a leaf: 1; otherwise left plus right17    return 0;18}19 20int main(void) {21    Node *t = node(8, node(3, node(1, NULL, NULL), node(6, node(4, NULL, NULL), node(7, NULL, NULL))),22                      node(10, NULL, node(14, NULL, NULL)));23    printf("%d\n", leaves(t));24    return 0;25}
Output
Press Run or Ctrl+Enter
Exercise 2

The largest value

Finish max_val: return the largest value in the whole tree (the tree isn't empty).

It should print
20
exercise2.c
1#include <stdio.h>2#include <stdlib.h>3 4typedef struct Node {5    int val;6    struct Node *left, *right;7} Node;8 9Node *node(int v, Node *l, Node *r) {10    Node *n = malloc(sizeof(Node));11    n->val = v; n->left = l; n->right = r;12    return n;13}14 15int max_val(Node *t) {16    // take this one as the largest; if the left or right subtree isn't empty, ask it and compare17    return t->val;18}19 20int main(void) {21    Node *t = node(5, node(12, node(3, NULL, NULL), NULL),22                      node(7, node(20, NULL, NULL), node(1, NULL, NULL)));23    printf("%d\n", max_val(t));24    return 0;25}
Output
Press Run or Ctrl+Enter

The properties exams use

NameWhat it isNodes
Full (perfect) binary treeevery level filledexactly 2ʰ − 1 at height h
Complete binary treeevery level filled but the last, which fills left to rightheight ⌊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 but the root has one edge above it, so there are n − 1 edges; and the edges also number n₁ + 2n₂ (one below each node with one child, two below each with two). Put n = n₀ + n₁ + n₂ in, and out comes 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?

Summary

Take-away

Binary trees: each side a smaller tree

  • A node: val + left + right, NULL where there's no child
  • Ask the two subtrees, then combine; an empty tree answers at once
  • Each node visited once, O(n); the recursion is as deep as the tree is tall
  • n₀ = n₂ + 1; a full binary tree has 2ʰ − 1 nodes
1int count(Node *t) {2    if (t == NULL) return 0;3    return count(t->left) + count(t->right) + 1;4}