A binary tree has inorder H D B E A F C G I and postorder H D E B F I G C A. Find its preorder.
A binary tree gives each node at most a left and a right child. Its counting properties (n₀ = n₂ + 1, 2ʰ⁺¹ − 1 nodes), four traversals, tree reconstruction from traversals and the binary search tree are PSC favourites.
A tree is a non-linear, hierarchical structure. Recursively: a tree is a finite set of one or more nodes with one special node, the root, and the remaining nodes partitioned into n ≥ 0 disjoint sets, each of which is itself a tree (a subtree of the root). Deleting the root of a tree leaves a forest — a set of n ≥ 0 disjoint trees. We will use this tree throughout the topic:
A
/ \
B C
/ \ \
D E F
/
G| Term | Definition | In the example |
|---|---|---|
| Root | the only node with no parent | A |
| Parent, child, siblings | a node directly above / below; children of the same parent | B is the parent of D and E; D and E are siblings |
| Ancestors, descendants | all nodes on the path up to the root / all nodes below | ancestors of G: E, B, A; descendants of B: D, E, G |
| Leaf (terminal, external node) | a node with no children | D, G, F |
| Internal (non-terminal) node | a node with at least one child | A, B, C, E |
| Degree of a node | number of its children | deg(B) = 2, deg(C) = 1, deg(G) = 0 |
| Degree of the tree | maximum degree of any node | 2 |
| Path, path length | sequence of nodes joined by edges; length = number of edges | A–B–E–G has length 3 |
| Depth of a node | edges from the root to the node | depth(A) = 0, depth(G) = 3 |
| Height of a node | edges on the longest downward path to a leaf | height(B) = 2, height(F) = 0 |
| Height of the tree | height of the root = maximum depth | 3 |
| Level | root at level 0 (CLRS, Weiss) or level 1 (Horowitz–Sahni) | G is on level 3, or level 4 |
A binary tree is either empty or consists of a root with a left subtree and a right subtree, each itself a binary tree. Every node therefore has at most two children, and the two positions are distinguished: a root whose only child is on the left is a different binary tree from one whose only child is on the right. (An ordinary tree has no such left/right distinction, and it cannot be empty.)
Why n₀ = n₂ + 1. Count the nodes: n = n₀ + n₁ + n₂. Count the edges two ways: every node except the root hangs from exactly one edge, so E = n − 1; and every degree-1 node starts one edge while every degree-2 node starts two, so E = n₁ + 2n₂. Equating, n₀ + n₁ + n₂ − 1 = n₁ + 2n₂, which simplifies to n₀ = n₂ + 1. The number of degree-1 nodes does not matter at all.
| Quantity | Root at level 0 / height in edges | Root at level 1 / depth in levels |
|---|---|---|
| Max nodes on level i | 2ⁱ | 2ⁱ⁻¹ |
| Max nodes in a tree with L levels | 2ᴸ − 1 (height h = L − 1 gives 2^(h+1) − 1) | 2ᴸ − 1 (depth k gives 2ᵏ − 1) |
| A perfect tree with 5 levels | height 4, 31 nodes | depth 5, 31 nodes |
| Max nodes on the 5th level | level 4: 16 | level 5: 16 |
How many binary trees? The number of differently shaped binary trees with n nodes is the Catalan number Cₙ = (2n)! / ((n + 1)!·n!) — 1, 2, 5, 14, 42 for n = 1 … 5. If the n nodes carry distinct labels, each shape can be labelled in n! ways, giving n!·Cₙ trees (30 for n = 3).
| Kind | Definition | Consequence |
|---|---|---|
| Full / strict / proper (2-tree) | every node has 0 or 2 children | n = 2I + 1 and leaves = I + 1 for I internal nodes |
| Complete | every level full except possibly the last, which is filled from the left without gaps | stored in an array with no gaps — heaps; height ⌊log₂ n⌋ |
| Perfect | every internal node has 2 children and all leaves are on the same level | exactly 2^(h+1) − 1 nodes |
| Skewed (left or right) | every node has only a left (or only a right) child | height n − 1; behaves like a linked list |
| Balanced (height-balanced) | at every node the two subtree heights differ by at most 1 | height O(log n) — the AVL condition |
| Extended binary tree | every empty subtree is replaced by a special external node | n internal nodes always have n + 1 external nodes |
Sequential (array) representation. Number the positions level by level, left to right, as if the tree were perfect. With 1-based indices the root is at 1 and the node at index i has children at 2i and 2i + 1 and its parent at ⌊i/2⌋ (0-based: 2i + 1, 2i + 2 and ⌊(i − 1)/2⌋). No pointers are stored. This is ideal for complete trees, which fill the array without gaps, but wasteful for skewed trees: a right-skewed tree with 4 nodes occupies positions 1, 3, 7 and 15, so 15 cells hold 4 nodes.
| Index | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
|---|---|---|---|---|---|---|---|---|---|---|
| Node | A | B | C | D | E | — | F | — | — | G |
Linked representation. Each node is a structure holding the data and two pointers, left and right (sometimes also a parent pointer). Memory grows with the actual number of nodes and any shape is handled, at the cost of two pointers per node — of the 2n pointers, n − 1 point to children and n + 1 are NULL.
A traversal visits every node exactly once. The three depth-first traversals differ only in when the root is visited relative to its two subtrees (the left subtree is always handled before the right): preorder = Node, Left, Right (NLR); inorder = Left, Node, Right (LNR); postorder = Left, Right, Node (LRN). Level order visits the nodes level by level, left to right — a breadth-first search that uses a queue.
#include <stdio.h>
#include <stdlib.h>
struct TNode { char data; struct TNode *left, *right; };
struct TNode *node(char d, struct TNode *l, struct TNode *r) {
struct TNode *p = malloc(sizeof *p);
if (!p) exit(1);
p->data = d; p->left = l; p->right = r;
return p;
}
void preorder(struct TNode *t) { if (t) { printf("%c ", t->data); preorder(t->left); preorder(t->right); } }
void inorder(struct TNode *t) { if (t) { inorder(t->left); printf("%c ", t->data); inorder(t->right); } }
void postorder(struct TNode *t) { if (t) { postorder(t->left); postorder(t->right); printf("%c ", t->data); } }
void levelorder(struct TNode *root) { /* breadth-first, array queue */
struct TNode *q[100];
int front = 0, rear = 0;
if (root) q[rear++] = root;
while (front < rear) {
struct TNode *t = q[front++];
printf("%c ", t->data);
if (t->left) q[rear++] = t->left;
if (t->right) q[rear++] = t->right;
}
}
int height(struct TNode *t) { /* edges; empty tree = -1 */
if (t == NULL) return -1;
int hl = height(t->left), hr = height(t->right);
return 1 + (hl > hr ? hl : hr);
}
int leaves(struct TNode *t) {
if (t == NULL) return 0;
if (t->left == NULL && t->right == NULL) return 1;
return leaves(t->left) + leaves(t->right);
}
int main(void) { /* the example tree */
struct TNode *root = node('A',
node('B', node('D', NULL, NULL), node('E', node('G', NULL, NULL), NULL)),
node('C', NULL, node('F', NULL, NULL)));
printf("pre: "); preorder(root); printf("\n"); /* A B D E G C F */
printf("in: "); inorder(root); printf("\n"); /* D B G E A C F */
printf("post: "); postorder(root); printf("\n"); /* D G E B F C A */
printf("level: "); levelorder(root); printf("\n"); /* A B C D E F G */
printf("height=%d leaves=%d\n", height(root), leaves(root)); /* height=3 leaves=3 */
return 0;
}| Traversal | Rule | Order |
|---|---|---|
| Preorder | N L R | A B D E G C F |
| Inorder | L N R | D B G E A C F |
| Postorder | L R N | D G E B F C A |
| Level order | level by level, left to right | A B C D E F G |
Euler-tour shortcut. Draw a line hugging the tree, starting to the left of the root and travelling anticlockwise around every node. List a node when the line passes its left side for preorder, its underside for inorder, and its right side for postorder. Each traversal takes O(n) time; the recursion stack grows to the tree's height, so space is O(h) — O(log n) for a balanced tree, O(n) for a skewed one. Inorder can also be done iteratively with an explicit stack: push the left spine, pop and visit, then move to the right child.
Worked: preorder A B D G C E H F and inorder D G B A H E C F. The root is A; inorder splits into {D, G, B} on the left and {H, E, C, F} on the right, so the preorder splits into B D G and C E H F. The left subtree's root is B with inorder D G B — everything is to B's left, so B has no right child; its left subtree has preorder D G and inorder D G, so D has right child G. The right subtree's root is C with inorder H E | C | F: left part H E with root E (H is E's left child) and right part F.
A
/ \
B C
/ / \
D E F
\ /
G H#include <stdio.h>
#include <string.h>
void postFromPreIn(const char *pre, const char *in, int n) {
if (n <= 0) return;
int r = (int)(strchr(in, pre[0]) - in); /* root's position in inorder */
postFromPreIn(pre + 1, in, r); /* left subtree: r nodes */
postFromPreIn(pre + 1 + r, in + r + 1, n - r - 1); /* right subtree */
printf("%c", pre[0]); /* the root comes last */
}
int main(void) {
postFromPreIn("ABDGCEHF", "DGBAHECF", 8);
printf("\n"); /* GDBHEFCA */
return 0;
}Uniqueness. Inorder together with preorder, postorder or level order determines a unique binary tree. Preorder together with postorder does not: a root A with a single child B has preorder A B and postorder B A whether B is the left or the right child. (It does determine the tree when every node has 0 or 2 children.) For a BST, preorder alone is enough, because the inorder is simply the keys in sorted order.
Expression trees store an arithmetic expression with operands at the leaves and operators at the internal nodes. To build one from postfix, scan left to right: an operand becomes a one-node tree pushed on a stack; an operator pops a right subtree and then a left subtree, joins them under a new node and pushes the result. For a b + c d e / - * the root is the multiplication, its left subtree is a + b and its right subtree is c − (d / e). Its preorder is * + a b - c / d e (prefix), its inorder with brackets is (a + b) × (c − d / e), and evaluating the tree means a postorder walk.
A binary search tree (BST) is a binary tree in which, for every node, all keys in the left subtree are smaller than the node's key and all keys in the right subtree are larger (duplicates are either forbidden or always sent to the same side). Consequently the inorder traversal lists the keys in ascending order, the minimum is the leftmost node and the maximum the rightmost node.
Search compares the key with the root: equal means found, smaller means continue in the left subtree, larger means the right subtree, and reaching NULL means the key is absent. Insertion performs the same search and attaches a new leaf where the search fell off the tree. Inserting 50, 30, 70, 20, 40, 60, 80, 65 in that order gives the tree below.
50
/ \
30 70
/ \ / \
20 40 60 80
\
65#include <stdio.h>
#include <stdlib.h>
struct Node { int key; struct Node *left, *right; };
struct Node *newNode(int k) {
struct Node *p = malloc(sizeof *p);
if (!p) exit(1);
p->key = k; p->left = p->right = NULL;
return p;
}
struct Node *insert(struct Node *t, int k) { /* O(h) */
if (t == NULL) return newNode(k);
if (k < t->key) t->left = insert(t->left, k);
else if (k > t->key) t->right = insert(t->right, k);
return t; /* duplicates ignored */
}
struct Node *search(struct Node *t, int k) { /* O(h), iterative */
while (t != NULL && t->key != k)
t = (k < t->key) ? t->left : t->right;
return t;
}
struct Node *minNode(struct Node *t) { /* leftmost node */
while (t->left != NULL) t = t->left;
return t;
}
struct Node *deleteKey(struct Node *t, int k) {
if (t == NULL) return NULL;
if (k < t->key) t->left = deleteKey(t->left, k);
else if (k > t->key) t->right = deleteKey(t->right, k);
else if (t->left == NULL || t->right == NULL) { /* cases 1 and 2 */
struct Node *child = t->left ? t->left : t->right;
free(t);
return child; /* NULL for a leaf */
} else { /* case 3 */
struct Node *s = minNode(t->right); /* inorder successor */
t->key = s->key;
t->right = deleteKey(t->right, s->key);
}
return t;
}
void inorder(struct Node *t) { if (t) { inorder(t->left); printf("%d ", t->key); inorder(t->right); } }
void preorder(struct Node *t) { if (t) { printf("%d ", t->key); preorder(t->left); preorder(t->right); } }
int main(void) {
int keys[] = {50, 30, 70, 20, 40, 60, 80, 65};
struct Node *root = NULL;
for (int i = 0; i < 8; i++) root = insert(root, keys[i]);
inorder(root); printf("\n"); /* 20 30 40 50 60 65 70 80 */
root = deleteKey(root, 20); /* case 1: leaf */
root = deleteKey(root, 30); /* case 2: one child (40) */
root = deleteKey(root, 50); /* case 3: successor is 60 */
preorder(root); printf("\n"); /* 60 40 70 65 80 */
printf("%s\n", search(root, 65) ? "65 found" : "65 missing");
return 0;
}| Delete | Case | What happens | Preorder afterwards |
|---|---|---|---|
| 20 | leaf | 30's left pointer becomes NULL | 50 30 40 70 60 65 80 |
| 30 | one child | 40 moves up to become 50's left child | 50 40 70 60 65 80 |
| 50 | two children | successor 60 (leftmost of the right subtree) is copied into the root; 60's old node is replaced by its child 65 | 60 40 70 65 80 |
Cost. Every operation follows one root-to-leaf path, so it costs O(h). For keys inserted in random order the expected height is O(log n), but inserting keys in sorted order produces a skewed tree of height n − 1 and O(n) operations — exactly the problem AVL and red–black trees solve. The number of distinct BSTs that can store n distinct keys is the Catalan number Cₙ (5 for 3 keys, 14 for 4 keys).
A linked binary tree with n nodes wastes n + 1 NULL pointers. Alan Perlis and Charles Thornton (1960) proposed using them as threads: a NULL right pointer is made to point to the node's inorder successor, and a NULL left pointer to its inorder predecessor. Each node gets two flag bits (lthread, rthread) to tell a thread from a genuine child pointer. Inorder traversal then needs neither recursion nor a stack — from any node, follow the right thread, or go right once and then left as far as possible.
| Node | Left pointer | Right pointer |
|---|---|---|
| D | thread → none (first node; header in a threaded tree with a header) | thread → B |
| G | thread → B | thread → E |
| E | child G | thread → A |
| C | thread → A | child F |
| F | thread → C | thread → none (last node; header) |
In a one-way (right-threaded) tree only the right NULL links become threads; in a two-way threaded tree both do. A header node is usually added so that the two loose threads (before the first and after the last inorder node) have somewhere to point. Insertion and deletion become slightly more complex because threads must be maintained.
Try the problem first, then reveal the working one step at a time.
A binary tree has inorder H D B E A F C G I and postorder H D E B F I G C A. Find its preorder.
Insert 45, 20, 60, 10, 30, 50, 70, 25 into an empty BST. Give its preorder, then delete 20 using the inorder successor and give the new preorder.
A binary tree has 20 leaves and 10 nodes with exactly one child. How many nodes have two children? How many nodes, edges and NULL links does the tree have?
List every BST that stores the keys 1, 2, 3 and check the count against the Catalan formula.
The preorder traversal of a BST is 40, 25, 10, 30, 28, 60, 50, 70, 65. Construct the tree and give its postorder traversal.
Using height in edges (single node = 0), give the maximum and minimum number of nodes in a binary tree of height 4. If instead the root is on level 1, how many nodes can level 4 hold, and how many nodes can a tree with 5 levels hold?
How many distinct BSTs can store 4 distinct keys? How many distinct binary trees can be formed with 3 labelled nodes?
In the BST of the first exercise (root 40), delete 40 (a) using the inorder successor, (b) using the inorder predecessor. Give the preorder in each case.
A right-skewed binary tree has 4 nodes. How many cells does its 1-based array representation need? What would a complete binary tree with 4 nodes need?
12 questions. 70 % passes the topic quiz (+30 XP, +20 more for 100 %). Exam scoring: +1 correct, −⅓ wrong.
Modelled on real KPSC questions (reworded) with the same concept and answer; each links to its original paper.