6.6Tree Applications
Rebuilding a tree from its traversals
One of the favourite tree questions in exams goes: "Draw the binary tree whose preorder is this and whose inorder is that." One traversal alone does not fix a tree, but given inorder together with preorder or postorder, the tree is unique. In this lesson you rebuild the tree by hand and with a recursive function.
- How preorder shows the root and inorder shows the left and right subtrees
- How to rebuild the tree recursively from these two
- How to use postorder instead, and why preorder with postorder is not enough
1Idea
The idea rests on two observations. A preorder traversal writes the root first: the first element of the preorder list is the root of the tree. An inorder traversal writes the root between its left and right subtrees: in the inorder list, everything to the left of the root is in the left subtree and everything to its right is in the right subtree.
Example: preorder 10 20 40 50 30 60, inorder 40 20 50 10 60 30.
- The first in preorder is 10: the root is 10. In inorder,
40 20 50is to the left of 10 and60 30is to its right. - The left subtree has three elements. In preorder the three elements after the root,
20 40 50, are its preorder; the first one, 20, is the root of the left subtree. In the inorder40 20 50, 40 is left of 20 and 50 is right of it: both are leaves. - The right subtree is
60 30. The remaining preorder is30 60; its first element, 30, is the root of the right subtree. In the inorder60 30, 60 is to the left of 30 and nothing is to its right: 60 is the left child and the right child is empty.
Each step does the same job: take the root from preorder, find it in inorder, repeat the job for both sides. That is recursion. The code reads the preorder list once from start to end; the next element is always the root of the next subtree to build, because preorder writes the root, then the whole left subtree, then the whole right subtree. That is why the left subtree must be built before the right one.
Postorder and inorder
Postorder writes the root last. So the last element of the postorder list is the root. When you build, you read postorder from the end backwards and build the right subtree first, then the left one. Everything else stays the same.
Why are preorder and postorder not enough?
Let preorder be 1 2 and postorder 2 1. The root is 1 and its child is 2; but is 2 the left child or the right child? Both trees give the same traversals. Only inorder carries the information that tells left from right. In a full tree, where every node has 0 or 2 children, this ambiguity cannot happen, and preorder with postorder is enough.
This method works when all values are different. If a value appears twice, the position of the root in inorder becomes ambiguous.
2Step by step
The top row is the inorder list, with the tree being built below it. Each node sits under its cell in inorder. Orange cells are the range of the subtree being built, green ones have been used as roots, faded ones are outside the range. Preorder: 10 20 40 50 30 60.
- build is called:
pis 0 and the range is the whole inorder list (0..5). - The next element in preorder is 10: it becomes the root. It is found at index 3 in inorder. 0..2 on its left is the left subtree, 4..5 on its right the right subtree.
- The left subtree is built with range 0..2. The next in preorder is 20, the root of this subtree; it is at index 1 in inorder. It becomes the left child of 10.
- 20's left, range 0..0. The next is 40: it becomes the root. Both sides are empty ranges (lo > hi), both calls return NULL: 40 is a leaf.
- 20's right, range 2..2. The next, 50, is built as a leaf. The left subtree of 10 is done.
- 10's right, range 4..5. The next is 30, at index 5 in inorder. 4..4 is on its left, an empty range on its right.
- 30's left, range 4..4. The next, 60, becomes a leaf. 30's right is 6..5, empty: NULL.
- The whole preorder has been read, and each call returned its root. The tree is built; its root is 10.
struct TreeNode { int data; struct TreeNode* left; struct TreeNode* right;}; struct TreeNode* newNode(int value) { struct TreeNode* n = malloc(sizeof(struct TreeNode)); n->data = value; n->left = NULL; n->right = NULL; return n;} // *p: next element in preorder, lo..hi: the subtree's range in inorderstruct TreeNode* subtree(int pre[], int* p, int ino[], int lo, int hi) { if (lo > hi) return NULL; // empty subtree struct TreeNode* root = newNode(pre[*p]); // next in preorder is the root (*p)++; int k = lo; while (ino[k] != root->data) k++; // find the root in inorder root->left = subtree(pre, p, ino, lo, k - 1); // the ones on its left root->right = subtree(pre, p, ino, k + 1, hi); // the ones on its right return root;} struct TreeNode* build(int pre[], int ino[], int n) { int p = 0; return subtree(pre, &p, ino, 0, n - 1);}class TreeNode { int data; TreeNode left, right; TreeNode(int data) { this.data = data; }} int p; // index of the next element in preorder TreeNode subtree(int[] pre, int[] ino, int lo, int hi) { if (lo > hi) return null; // empty subtree TreeNode root = new TreeNode(pre[p]); // next in preorder is the root p++; int k = lo; while (ino[k] != root.data) k++; // find the root in inorder root.left = subtree(pre, ino, lo, k - 1); // the ones on its left root.right = subtree(pre, ino, k + 1, hi); // the ones on its right return root;} TreeNode build(int[] pre, int[] ino) { p = 0; return subtree(pre, ino, 0, ino.length - 1);}class TreeNode: def __init__(self, data): self.data = data self.left = None self.right = None def build(pre, ino): p = 0 # index of the next element in preorder def subtree(lo, hi): nonlocal p if lo > hi: return None # empty subtree root = TreeNode(pre[p]) # next in preorder is the root p += 1 k = lo while ino[k] != root.data: # find the root in inorder k += 1 root.left = subtree(lo, k - 1) # the ones on its left root.right = subtree(k + 1, hi) # the ones on its right return root return subtree(0, len(ino) - 1)The snippets focus on the operation in this lesson. The C examples need stdlib.h.
3Complexity
Each node is created once, but finding the root in inorder scans the range from its start. On a skewed tree these scans add up to n + (n - 1) + ... + 1 steps, which is O(n²). On a balanced tree it is O(n log n).
n nodes are created. The recursion goes as deep as the height of the tree; n in the worst case.
If you first put the inorder index of every value into a dictionary (a hash table), you find each root in O(1) and the time drops to O(n).
4Common mistake
The most common mistake when building from preorder is to build the right subtree first:
root->right = subtree(pre, p, ino, k + 1, hi); // wrong orderroot->left = subtree(pre, p, ino, lo, k - 1);In preorder, every element of the left subtree comes right after the root. If the right subtree is built first, the next element, which is the root of the left subtree, is placed on the right and looked for in the wrong range of inorder. When building from postorder the opposite holds: right first.
5Try it
Preorder A B D E C F, inorder D B E A F C. What is C's left child?
The answer is A. The root is A. In inorder, F C is to the right of A. That subtree's preorder is C F, so its root is C. In the inorder F C, F is to the left of C: F is the left child.
Show the answer
The answer is A. The root is A. In inorder, F C is to the right of A. That subtree's preorder is C F, so its root is C. In the inorder F C, F is to the left of C: F is the left child.
Which two traversals always fix a single binary tree?
The answer is B. Postorder gives the root and inorder splits its two sides. Preorder with postorder cannot tell whether the only child of a node is on the left or the right.
Show the answer
The answer is B. Postorder gives the root and inorder splits its two sides. Preorder with postorder cannot tell whether the only child of a node is on the left or the right.
Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.