Kodewick
Start learning →
Patterns: trees27 / 50

Patterns: trees

Lesson 27 of 50 · Part 5 · Trees · about 18 minutes

This tree review shows that most binary tree problems are one recursive template (what an empty tree returns and how the left and right answers combine), then what each of the four traversals is good for, and the formulas exams use, such as n₀ = n₂ + 1.

Tree problems look endlessly varied: depth, symmetry, paths, inverting, ancestors… but in interviews and exams most are one template; the rest is choosing a traversal and a few formulas. This lesson has four sections, one pattern each.

Pattern one: ask left and right, combine

Writing tree recursion takes two decisions:

  1. What an empty tree gives (the answer at the bottom of the recursion);
  2. Given the left and right subtrees' answers, how to make this node's.
To work outAn empty tree givesHow to combine
Number of nodes0left + right + 1
Height0max(left, right) + 1
Number of leaves01 for a leaf, otherwise left + right
Sum of all values0left + right + this value
Is there a node with value xnothis one is x, or left has it, or right has it
Are two trees the samethe same only if both are emptythe same root, and left same as left, right as right

The other kind passes things down: a parameter carries "what we know from the root to here" downwards, like the sum along the path, or the range allowed (lo and hi in last lesson's binary search tree check). Combining is postorder thinking, passing down is preorder thinking, and many problems use both.

4
2
1
3
7
6
9

Inverting a binary tree: every node swaps its left and right children. Invert both subtrees first, then swap them over
Fill inTap one to fill a blank; tap a blank to take it back

The template for height: an empty tree is 0; once you have the heights l and r of the two subtrees, what is this node's height? The tree is 1 (left child 2, right child 3); 2 has only a right child, 4, and 3 has only a left child, 5.

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 height(Node *t) {16    if (!t) return 0;17    int l = height(t->left), r = height(t->right);18    return ;19}20 21int main(void) {22    Node *t = node(1, node(2, NULL, node(4, NULL, NULL)), node(3, node(5, NULL, NULL), NULL));23    printf("%d\n", height(t));24    return 0;25}
Exercise 1

Invert a binary tree

Finish invert: invert both subtrees first, then swap the left and right pointers. Inverted, its inorder should run largest to smallest.

It should print
9 7 6 4 3 2 1
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 15void invert(Node *t) {16    // an empty tree returns; invert the left, invert the right; swap t->left and t->right17}18 19void in(Node *t) {20    if (!t) return;21    in(t->left);22    printf("%d ", t->val);23    in(t->right);24}25 26int main(void) {27    Node *t = node(4, node(2, node(1, NULL, NULL), node(3, NULL, NULL)),28                      node(7, node(6, NULL, NULL), node(9, NULL, NULL)));29    invert(t);30    in(t);31    printf("\n");32    return 0;33}
Output
Press Run or Ctrl+Enter
Exercise 2

Path sum

Is there a path from the root to a leaf whose values add up to exactly sum? Pass "how much is still missing" down: at a leaf, see whether what's missing is exactly its value.

It should print
1 1 0
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 has_sum(Node *t, int sum) {16    // empty: 0; a leaf: sum == t->val; otherwise look for sum - t->val on the left and the right17    return 0;18}19 20int main(void) {21    //        522    //      4   823    //    11   13 424    //   7  2       125    Node *t = node(5, node(4, node(11, node(7, NULL, NULL), node(2, NULL, NULL)), NULL),26                      node(8, node(13, NULL, NULL), node(4, NULL, node(1, NULL, NULL))));27    printf("%d %d %d\n", has_sum(t, 22), has_sum(t, 26), has_sum(t, 9));28    return 0;29}
Output
Press Run or Ctrl+Enter

Pattern two: the right traversal

TraversalGood forFor example
Preorderthis node first, then the children: passing things down, copying a treeprinting a folder tree, path sums
Inordera binary search tree smallest to largestthe k-th smallest, checking a binary search tree
Postorderneeds the children's answers: height, deleting and freeingfreeing a whole tree, subtree sizes
Level orderby level, nearest the rooteach level's largest, the minimum depth

Freeing a whole tree has to be postorder: free the two children first, this node last. free(t) first and then t->left reads memory already handed back (the dangling pointer from Chapter 1).

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 9int freed = 0;10 11Node *node(int v, Node *l, Node *r) {12    Node *n = malloc(sizeof(Node));13    n->val = v; n->left = l; n->right = r;14    return n;15}16 17void free_tree(Node *t) {18    if (!t) return;19    free_tree(t->left);      // the children first20    free_tree(t->right);21    printf("free %d\n", t->val);22    free(t);                 // this one last: postorder23    freed++;24}25 26int main(void) {27    Node *t = node(1, node(2, node(4, NULL, NULL), NULL), node(3, NULL, NULL));28    free_tree(t);29    printf("%d freed in all\n", freed);30    return 0;31}
Output
free 4
free 2
free 3
free 1
4 freed in all
Choose one

To find the 3rd smallest value in a binary search tree, which traversal fits best?

Pattern three: the formulas exam questions use

The question asksFormula
Leaves against nodes of degree 2n₀ = n₂ + 1
The most nodes in a binary tree of height h2ʰ − 1
The height of a complete binary tree of n nodes⌊log₂ n⌋ + 1
How many leaves a complete binary tree of n nodes has⌈n / 2⌉
Node i's children and parent in a complete binary tree (numbered from 1)2i, 2i + 1; ⌊i / 2⌋
How many nodes a Huffman tree with n leaves has2n − 1
How many shapes of binary tree n nodes can makethe Catalan number C(2n, n) / (n + 1), 5 for n = 3
Choose one

A binary tree has 6 nodes of degree 2. How many leaves does it have?

Choose one

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

Pattern four: in a BST, compare and then go

A binary search tree comes with one more rule: everything in the left subtree is smaller than the root, everything in the right subtree bigger. So many problems don't need both sides: compare with the current node and the answer can only be on one side. One path down is enough, which takes O(h) (h is the height), not O(n). Search, insert, the minimum (keep going left) and the maximum (keep going right) all look like this:

1while (t) {2    if (x < t->val) t = t->left;          // can only be on the left3    else if (x > t->val) t = t->right;    // can only be on the right4    else return t;                        // this is it5}

The lowest common ancestor works the same way: if p and q are both smaller than the current node, go left; if both are bigger, go right. When one is on the left and one on the right (or one of them is the node itself), this is where the two values part ways, and the current node is the answer.

6
2
0
4
3
5
8
7
9

The BST built by inserting 6 2 8 0 4 7 9 3 5: finding the lowest common ancestor of 3 and 5 takes a single path
Choose one

In this section's tree (6 2 8 0 4 7 9 3 5 inserted in that order), what is the lowest common ancestor of 7 and 9?

Exercise 3

The lowest common ancestor in a binary search tree

The lowest common ancestor of p and q is, walking down from the root, the first node that puts them on different sides (or is one of them). Both smaller than the node, go left; both bigger, go right; otherwise it's this one.

It should print
6 4 2
exercise3.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 *insert(Node *t, int v) {10    if (!t) {11        t = malloc(sizeof(Node));12        t->val = v;13        t->left = t->right = NULL;14    } else if (v < t->val) t->left = insert(t->left, v);15    else if (v > t->val) t->right = insert(t->right, v);16    return t;17}18 19int lca(Node *t, int p, int q) {20    // a loop: p and q both < t->val, go left; both >, go right; otherwise return t->val21    return t->val;22}23 24int main(void) {25    int a[] = {6, 2, 8, 0, 4, 7, 9, 3, 5};26    Node *t = NULL;27    for (int i = 0; i < 9; i++) t = insert(t, a[i]);28    printf("%d %d %d\n", lca(t, 2, 8), lca(t, 3, 5), lca(t, 2, 4));29    return 0;30}
Output
Press Run or Ctrl+Enter

Summary

Take-away

Four tree patterns

  • The template: what an empty tree gives + how left and right combine; or pass things down
  • Inorder = a BST smallest to largest; postorder = wait for the children (height, freeing); level order = by level
  • Formulas: n₀ = n₂ + 1, 2ʰ − 1, ⌊log₂ n⌋ + 1, Huffman 2n − 1
  • Free a tree in postorder: the children first, then this one
  • A BST: compare with the current node and go down one side only, O(h)
1int f(Node *t) {2    if (!t) return the empty tree's answer;3    int l = f(t->left), r = f(t->right);4    return l, r and t->val combined;5}

Chapter 4 quick check

5 questions: a traversal, a binary search tree's shape, a heap's array, a Huffman WPL, and the leaves of a complete binary tree. Work out what each prints before you pick.

Guess the outputA wrong guess is fine

1's left child is 2 (2 has only a right child, 4), its right child 3 (3 has only a left child, 5). What does postorder 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 15void post(Node *t) {16    if (!t) return;17    post(t->left);18    post(t->right);19    printf("%d ", t->val);20}21 22int main(void) {23    Node *t = node(1, node(2, NULL, node(4, NULL, NULL)), node(3, node(5, NULL, NULL), NULL));24    post(t);25    printf("\n");26    return 0;27}
Guess the outputA wrong guess is fine

Insert 10 9 8 20 30 40 7 in that order: how tall is the binary search tree?

1#include <stdio.h>2#include <stdlib.h>3 4typedef struct Node {5    int val;6    struct Node *left, *right;7} Node;8 9Node *insert(Node *t, int v) {10    if (!t) {11        t = malloc(sizeof(Node));12        t->val = v;13        t->left = t->right = NULL;14    } else if (v < t->val) t->left = insert(t->left, v);15    else if (v > t->val) t->right = insert(t->right, v);16    return t;17}18 19int height(Node *t) {20    if (!t) return 0;21    int l = height(t->left), r = height(t->right);22    return (l > r ? l : r) + 1;23}24 25int main(void) {26    int a[] = {10, 9, 8, 20, 30, 40, 7};27    Node *t = NULL;28    for (int i = 0; i < 7; i++) t = insert(t, a[i]);29    printf("%d\n", height(t));30    return 0;31}
Guess the outputA wrong guess is fine

Put 5 3 8 1 2 into an empty min-heap, in that order. What does the array look like?

1#include <stdio.h>2 3int h[10], n = 0;4 5void push(int v) {6    int i = n++;7    h[i] = v;8    while (i > 0 && h[(i - 1) / 2] > h[i]) {9        int t = h[i]; h[i] = h[(i - 1) / 2]; h[(i - 1) / 2] = t;10        i = (i - 1) / 2;11    }12}13 14int main(void) {15    int a[] = {5, 3, 8, 1, 2};16    for (int i = 0; i < 5; i++) push(a[i]);17    for (int i = 0; i < n; i++) printf("%d ", h[i]);18    printf("\n");19    return 0;20}
Guess the outputA wrong guess is fine

The Huffman tree for weights 2, 3, 5, 7: what is its WPL?

1#include <stdio.h>2 3int main(void) {4    int w[] = {2, 3, 5, 7};5    int n = 4, wpl = 0;6    while (n > 1) {7        int x = 0, y = 1;8        if (w[y] < w[x]) { x = 1; y = 0; }9        for (int i = 2; i < n; i++)10            if (w[i] < w[x]) { y = x; x = i; }11            else if (w[i] < w[y]) y = i;12        int s = w[x] + w[y];13        wpl += s;14        w[x] = s;15        w[y] = w[n - 1];16        n--;17    }18    printf("%d\n", wpl);19    return 0;20}
Guess the outputA wrong guess is fine

A complete binary tree of 10 nodes kept in an array (indexes 0 to 9): how many leaves?

1#include <stdio.h>2 3int main(void) {4    int n = 10, leaves = 0;5    for (int i = 0; i < n; i++)6        if (2 * i + 1 >= n)      // its left child's index is past the end: no children7            leaves++;8    printf("%d\n", leaves);9    return 0;10}