Binary Trees, Traversals and Choosing a Structure

IB Computer Science · Abstract Data Structures (HL)

Terminology. A binary tree consists of nodes, each with at most two children. The root is the single node with no parent; a leaf has no children; the depth of a node is the number of edges from the root; the height of the tree is the depth of its deepest node. Any node together with everything below it forms a subtree, which is why almost every tree algorithm is naturally recursive: a tree is a node plus two smaller trees.

The binary search tree property. In a binary search tree, everything in a node's left subtree is smaller than the node and everything in its right subtree is larger. Inserting a value starts at the root and moves left or right at each node until an empty position is reached. Searching uses the same comparison at each step, and because each comparison eliminates an entire subtree, a balanced tree of n nodes is searched in about log base 2 of n steps.

The crucial caveat. That efficiency depends entirely on balance. If values are inserted in sorted order, every new value goes to the right and the tree degenerates into a straight chain — functionally a linked list — so searching takes n steps. This is why real systems use self-balancing trees, and why an answer claiming that binary search trees are logarithmic without stating the balance condition is incomplete.

Traversals. The three orders are named after the position of the node relative to its subtrees, and the left subtree is always handled before the right. Pre-order is node, left, right; it records a parent before its children, so it is the correct order to copy or serialise a tree. In-order is left, node, right; on a binary search tree it outputs the values in sorted order. Post-order is left, right, node; it processes both children before the node, which is what is required to free memory safely and to evaluate an expression tree, since both operands must be known before the operator is applied.

Choosing a structure. The decision follows from the operations required. Direct access by position points to an array. Frequent insertion and deletion in the middle points to a linked list. A need to reverse or to return to a previous state points to a stack. Fair service in arrival order points to a queue. A need to keep data ordered while still inserting and searching quickly points to a tree. Naming the operation that dominates is what earns the mark, not naming the structure.

BINARY SEARCH TREE AND THE THREE TRAVERSALS 50 30 70 20 40 60 80 Rule: the LEFT branch is smaller than the node, the RIGHT branch is greater than the node PREORDER — Node, Left, Right 50 · 30 · 20 · 40 · 70 · 60 · 80 used to COPY a tree INORDER — Left, Node, Right 20 · 30 · 40 · 50 · 60 · 70 · 80 gives the SORTED order POSTORDER — Left, Right, Node 20 · 40 · 30 · 60 · 80 · 70 · 50 used to DELETE a tree · evaluate an expression SEARCH: each comparison eliminates a whole subtree — a BALANCED tree takes about log n steps BUT inserting already-sorted data creates a tree that DEGENERATES into a straight chain, and then search takes n steps Memory trick for the three traversals: the words PRE, IN, POST show the position of the NODE relative to its two subtrees The left branch is always processed before the right branch in all three orders
The three traversals are asked in almost every exam, and the memory trick is very simple: the words PRE, IN, POST show the position of the NODE relative to its two subtrees, and the left branch is always processed before the right branch in all three orders. Preorder is Node then Left then Right. Inorder is Left then Node then Right. Postorder is Left then Right then Node. Each traversal has its own use, and being able to state the use is where the marks are. Inorder on a binary search tree gives a sequence sorted in ascending order — this follows directly from the property that left is smaller than the node and right is greater than the node, and it turns a binary search tree into a sorting algorithm. Preorder records a parent node before its children, so it is the right order to copy or serialize a tree: reading back in exactly that order rebuilds the identical tree. Postorder processes both children before the node, so it is the right order to free memory — do not delete a parent while its children still reference it — and to evaluate an expression tree, because the results of the two operands must be available before the operator is applied. The warning in the red line is the point that separates strong candidates. People often say a binary search tree gives logarithmic-order search time, but that is only true when the tree is balanced. If already-sorted data is inserted — for example inserting 10, 20, 30, 40, 50 in turn — each new element always goes to the right and the tree degenerates into a straight chain, effectively a linked list, and search takes n steps rather than the logarithm of n. This is why real systems use self-balancing trees.

Worked example: Building a binary search tree and outputting the three traversals

Insert the values 45, 25, 60, 15, 35, 55, 70, 30 in turn into an empty binary search tree. Draw the tree, output the three traversals, then say what happens if the same set of values is inserted in ascending order.

Solution

Building the tree. The value 45 comes first so it becomes the root. The value 25 is less than 45 so it goes left. The value 60 is greater than 45 so it goes right. The value 15 is less than 45 and then less than 25 so it becomes the left child of 25. The value 35 is less than 45 and then greater than 25 so it becomes the right child of 25. The value 55 is greater than 45 and then less than 60 so it becomes the left child of 60. The value 70 is greater than 45 and then greater than 60 so it becomes the right child of 60. The value 30 is less than 45, greater than 25, less than 35 so it becomes the LEFT child of 35.

Tree structure. The root is 45. The left child of 45 is 25, the right child is 60. Node 25 has left child 15 and right child 35. Node 35 has left child 30. Node 60 has left child 55 and right child 70.

Preorder — node, left, right: 45, 25, 15, 35, 30, 60, 55, 70.

Inorder — left, node, right: 15, 25, 30, 35, 45, 55, 60, 70. Notice this result is sorted in ascending order, and that is no coincidence: the property that left is smaller than the node and right is greater than the node guarantees it for every binary search tree. It is also a quick way to check whether you built the tree correctly — if inorder does not give an ascending sequence, some node is certainly in the wrong place.

Postorder — left, right, node: 15, 30, 35, 25, 55, 70, 60, 45. Notice the root 45 is last, as expected because a node is always processed after its two subtrees.

If inserted in ascending order 15, 25, 30, 35, 45, 55, 60, 70. The value 15 becomes the root. The value 25 is greater so it goes right. The value 30 is greater than both 15 and 25 so it goes right again. Every later value is greater than all the existing nodes so it always goes right. The result is a straight chain going down to the right, with height 7 instead of 3.

Consequence. This degenerate tree is functionally a linked list. Finding the value 70 takes 8 comparisons instead of 3, that is, the search time moves from logarithmic order to linear order. The irony is that already-sorted data is the worst case for a binary search tree, even though it is the best case for binary search on an array. This is why real libraries use self-balancing trees, which rotate the structure after each insertion to keep the height at logarithmic order.

Worked example: Expression trees and why postorder is the correct order of evaluation

The expression (3 plus 5) times (10 minus 4) is represented by a tree in which the leaf nodes are operands and the internal nodes are operators. Describe the tree, output the three traversals, and explain why postorder is the correct order for evaluating the value.

Solution

Tree structure. The root is the multiplication operator, because it is the last operation performed. The left subtree of the root has the addition operator as its node with two leaves 3 and 5. The right subtree has the subtraction operator as its node with two leaves 10 and 4. General principle: the operator performed last sits at the root, and the tree structure already encodes the precedence so brackets are no longer needed.

Preorder — node, left, right: times, plus, 3, 5, minus, 10, 4. This is exactly prefix notation, also called Polish notation.

Inorder — left, node, right: 3, plus, 5, times, 10, minus, 4. This is the familiar infix notation, but notice one important thing: it has LOST its brackets, so reading this string back by the usual precedence rules would give 3 plus 5 times 10 minus 4, a completely different expression. This is why infix notation needs brackets while the other two notations do not.

Postorder — left, right, node: 3, 5, plus, 10, 4, minus, times. This is postfix notation, also called reverse Polish notation.

Why postorder is the correct order of evaluation. To apply an operator, you must know the values of both operands beforehand. Postorder guarantees exactly that, because it finishes both the left subtree and the right subtree before reaching the node. Preorder is the opposite: it meets the multiplication operator before knowing any operand, so it cannot compute immediately.

How a computer actually evaluates a postfix string, and this is the link to the stack. Read the string from left to right. When you meet an operand, push it onto the stack. When you meet an operator, pop the TWO top elements, apply the operator, then push the result back. Following the string 3, 5, plus, 10, 4, minus, times: push 3; push 5; meet plus so pop 5 and 3, compute 8, push 8; push 10; push 4; meet minus so pop 4 and 10, compute 6, push 6; meet times so pop 6 and 8, compute 48, push 48. The stack has exactly one value left and that is the result.

A note on operand order. For subtraction and division, order matters: the element popped FIRST is the SECOND operand. In the example above, pop 4 and then pop 10, and the correct calculation is 10 minus 4, not 4 minus 10. This is the most common error when tracing problems of this type.

Common mistake

Trap 1 — saying a binary search tree gives logarithmic-order search time without stating the BALANCED condition. Inserting already-sorted data creates a tree that degenerates into a straight chain and the search time becomes linear order.
Trap 2 — remembering the three traversals by memorizing the result sequences. Remember by the rule: the name shows the position of the NODE relative to the two subtrees, and the left subtree is always processed before the right subtree. From that rule you can derive the result for any tree.
Trap 3 — taking the operands in the wrong order when evaluating a postfix expression with a stack. The element popped FIRST is the SECOND operand of the operation. For addition and multiplication it does not matter, but for subtraction and division it is completely wrong.

Key takeaway

Lesson 2 wrap-up. Four things to take into the exam room. One, the property that left is smaller than the node and right is greater than the node, and the balance condition must be stated when discussing efficiency. Two, the three traversals are derived from a rule, not memorized, with the particular use of each: pre for copying, in for a sorted sequence, post for deleting and for evaluating expressions. Three, expression trees connect trees to stacks through postfix notation, and remember the operand order when popping. Four, the structure-choice framework: name the dominant operation first, then name the structure.

← Recursion, Stacks, Queues and Linked Lists · All IB Computer Science lessons · Practice IB Computer Science questions (free, instant scoring) · Recursive Algorithms on Trees and Lists →