Kodewick
Start learning →
Drawing a binary tree from its traversals22 / 50

Drawing a binary tree from its traversals

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

To draw a binary tree from its traversals, take the first value in preorder (or the last in postorder) as the root, let the inorder sequence split the rest into left and right subtrees, and repeat on each side; preorder plus postorder alone can't fix the tree.

Last lesson went "here's a tree, write its sequences". Exams like it the other way round even more: here are two sequences, draw the tree. Say the preorder is A B D E C F and the inorder D B E A C F: what does the tree look like?

Each sequence tells you one thing

  • The first in preorder is always the root (root, left, right: the root comes first). The last in postorder is the root too.
  • In inorder, everything left of the root is the left subtree and everything right of it the right subtree (left, root, right).

Knowing the root, you can split the inorder sequence in two; knowing how many are on the left, you can split the preorder sequence the same way. Then you do the same for each half.

preorder (left 6) and inorder (right 6)preorderinorderABDECFDBEACF01234567891011

Preorder A B D E C F, inorder D B E A C F: find the root A, then split both sequences into the left subtree and the right
A

Half by half, the tree draws itself

Check it with the third traversal: this tree's postorder should be D E B F C A.

Choose one

The preorder is A B D C E F and the inorder B D A E C F. Draw the tree: what is its postorder?

Choose one

The postorder is C B E F D A and the inorder B C A E D F. What is the preorder?

Put in orderDrag, or use the arrows

Drawing a tree from its preorder and inorder: put the four steps in order.

  1. Do the same again for each of the two parts
  2. Count k nodes in the left subtree: the k after the root in the preorder are the left subtree, the rest the right one
  3. Find the root in the inorder: what is left of it is the left subtree, what is right of it the right subtree
  4. Take the first in the preorder: it is the root

In C

The steps turn straight into a recursion: build(pre, in, n) builds a tree from two sequences of length n. The root is pre[0]; find it in in at position k; the left subtree uses pre + 1 and the first k of in, the right subtree the remaining n − 1 − k.

pre · inpreinABDECFDBEACF01234567891011

build("ABDECF", "DBEACF", 6): the root A is at index 3 of the inorder, so k = 3; both sequences are cut into 3 on the left and 2 on the right
main.c
1#include <stdio.h>2#include <stdlib.h>3 4typedef struct Node {5    char val;6    struct Node *left, *right;7} Node;8 9Node *build(const char *pre, const char *in, int n) {10    if (n == 0) return NULL;11    Node *t = malloc(sizeof(Node));12    t->val = pre[0];                 // the first in preorder is the root13    int k = 0;14    while (in[k] != pre[0]) k++;     // where the root is in inorder: k to its left15    t->left = build(pre + 1, in, k);16    t->right = build(pre + 1 + k, in + k + 1, n - 1 - k);17    return t;18}19 20void post(Node *t) {21    if (!t) return;22    post(t->left);23    post(t->right);24    printf("%c ", t->val);25}26 27int main(void) {28    Node *t = build("ABDECF", "DBEACF", 6);29    printf("postorder: ");30    post(t);31    printf("\n");32    return 0;33}
Output
postorder: D E B F C A 

Each level of the recursion searches the inorder sequence for the root once, which is O(n²) at worst (when the tree is a chain); note each value's position in an array first and it comes down to O(n).

Guess the outputA wrong guess is fine

Preorder A B C D, inorder D C B A. How tall is the tree it builds?

1#include <stdio.h>2#include <stdlib.h>3 4typedef struct Node {5    char val;6    struct Node *left, *right;7} Node;8 9Node *build(const char *pre, const char *in, int n) {10    if (n == 0) return NULL;11    Node *t = malloc(sizeof(Node));12    t->val = pre[0];13    int k = 0;14    while (in[k] != pre[0]) k++;15    t->left = build(pre + 1, in, k);16    t->right = build(pre + 1 + k, in + k + 1, n - 1 - k);17    return t;18}19 20int height(Node *t) {21    if (!t) return 0;22    int l = height(t->left), r = height(t->right);23    return (l > r ? l : r) + 1;24}25 26int main(void) {27    printf("%d\n", height(build("ABCD", "DCBA", 4)));28    return 0;29}
Fill inTap one to fill a blank; tap a blank to take it back

How many nodes are in the right subtree? Pick what goes in the blank so the program prints the tree's postorder, DEBFCA.

1#include <stdio.h>2#include <stdlib.h>3 4typedef struct Node {5    char val;6    struct Node *left, *right;7} Node;8 9Node *build(const char *pre, const char *in, int n) {10    if (n == 0) return NULL;11    Node *t = malloc(sizeof(Node));12    t->val = pre[0];13    int k = 0;14    while (in[k] != pre[0]) k++;15    t->left = build(pre + 1, in, k);16    t->right = build(pre + 1 + k, in + k + 1, );17    return t;18}19 20void post(Node *t) {21    if (!t) return;22    post(t->left);23    post(t->right);24    printf("%c", t->val);25}26 27int main(void) {28    post(build("ABDECF", "DBEACF", 6));29    printf("\n");30    return 0;31}
Choose one

How long does this step's build take in the worst case?

Exercise 1

Building from postorder and inorder

Finish build: build the tree from postorder and inorder. The root is the last in postorder; the left subtree is the first k of postorder, the right subtree the next n − 1 − k.

It should print
ABDCEGFH
exercise1.c
1#include <stdio.h>2#include <stdlib.h>3 4typedef struct Node {5    char val;6    struct Node *left, *right;7} Node;8 9Node *build(const char *post, const char *in, int n) {10    if (n == 0) return NULL;11    Node *t = malloc(sizeof(Node));12    t->val = post[n - 1];13    // find the root's position k in in, then build the two subtrees14    t->left = t->right = NULL;15    return t;16}17 18void pre(Node *t) {19    if (!t) return;20    printf("%c", t->val);21    pre(t->left);22    pre(t->right);23}24 25int main(void) {26    pre(build("DBGEHFCA", "BDAGECHF", 8));27    printf("\n");28    return 0;29}
Output
Press Run or Ctrl+Enter
Exercise 2

Postorder without building the tree

No tree this time: post_of splits the preorder and inorder sequences the same way, and prints in the order "left half, right half, root". What it prints is the postorder.

It should print
AEFDHZMG
exercise2.c
1#include <stdio.h>2 3void post_of(const char *pre, const char *in, int n) {4    // n == 0 returns; find the root's position k in inorder; the left half, the right half, then print the root pre[0]5}6 7int main(void) {8    post_of("GDAFEMHZ", "ADEFGHMZ", 8);9    printf("\n");10    return 0;11}
Output
Press Run or Ctrl+Enter

Which pairs fix a tree

GivenOne tree only?Why
preorder + inorderyespreorder gives the root, inorder splits left and right
postorder + inorderyesthe last in postorder is the root, inorder splits left and right
level order + inorderyesthe first in level order is the root, inorder splits left and right
preorder + postordernoyou know the root, but can't tell left from right

Why preorder + postorder fails: one tree is just A with a left child B, another just A with a right child B; both have preorder A B and postorder B A. Inorder is a must to tell left from right.

Two different trees: B is a left child in one and a right child in the other, yet both have the preorder A B and the postorder B A

In exams: with postorder + inorder, take the root from the end of postorder; once the two halves are split, the front part of postorder is the left subtree, followed by the right subtree, with the root last. Always check what you drew against the third traversal.

Choose one

A binary tree's preorder and postorder are exact reverses of each other (say, preorder A B C and postorder C B A). What must the tree look like?

Choose one

How many binary trees have the preorder A B C and the postorder C B A?

Summary

Take-away

A tree from two sequences: one gives the root, inorder splits it

  • The first in preorder / the last in postorder is the root
  • In inorder, left of the root is the left subtree, right of it the right; count the k on the left
  • Split the other sequence at k too, and do both halves again
  • Preorder + postorder can't pin a tree down: inorder is a must
1t->val = pre[0];2while (in[k] != pre[0]) k++;3t->left = build(pre + 1, in, k);4t->right = build(pre + 1 + k, in + k + 1, n - 1 - k);