Overview
This class covers how binary trees are stored in memory (link vs. sequential/array representation), the three depth-first traversals (pre-order, in-order, post-order) and how a stack is used to perform them, and the definition and construction of binary search trees (BSTs). It then works through BST insertion, searching complexity, duplicate removal, and all three deletion cases, including the in-order successor and cascading deletions. The class closes by motivating balanced trees: the skewness problem and the AVL tree with its balance factor. This material sits at the foundation of the tree unit — BST is described as the base on which AVL, RB, MV and B trees are built.
Learning outcomes
- Choose between link representation and sequential (array) representation for a tree based on its density.
- Perform pre-order, in-order and post-order traversals, including the stack-based procedure for each.
- Reconstruct a tree from pre-order + in-order or in-order + post-order pairs.
- State the formal BST property and build a BST by inserting a given list of keys.
- Explain why BST search is O(log n) on average and why skewness degrades it to order of n.
- Delete a node from a BST in all three cases (zero, one, two children), using the in-order successor.
- Explain the
availpointer behaviour in the memory/table representation during deletion. - Define an AVL tree and compute a node's balance factor.
- Count the edges of a tree with n nodes, the maximum nodes at a level or in a tree of height h, and the minimum height for n nodes.
- State the key capacity of an M-way search tree node and how insertion into one begins.
Core concepts
Tree representation in memory
Link representation is a form of doubly linked list: a left field pointing to the left child, a right field pointing to the right child, and an info part in between. Sequential representation stores the tree in a linear array using the policy k, 2k, 2k+1 on each node to determine node locations. Avail space is the addition of available memory "on the top" — the pointer points to the most recently deleted (most recently available) space. Choice rule: for a dense tree (complete or nearly complete) prefer sequential representation; for a sparse tree (connections not fully occupied, far from complete) prefer link representation. In the lab/coding, array representation is primarily used — it is more viable and easy to go. This matters because representation determines memory cost and access pattern for every operation that follows.
Tree counting facts
A tree with $n$ nodes has exactly $n-1$ edges: a tree is connected and acyclic, and every node except the root has exactly one incoming edge. A complete binary tree is one in which every level except possibly the last is completely filled, and the last level is filled from left to right; a perfect tree has all levels full, and a full/proper tree has every node with zero or two children. The maximum number of nodes in a binary tree of height $h$ (height counted in edges) is $2^{h+1}-1$; the minimum possible height for $n$ nodes is $\lceil \log_2(n+1) \rceil - 1$.
Traversal
Traversal means visiting all the nodes of the tree. Pre-order is root, left, right — the root appears at the first position. In-order is left, root, right — the root comes in between the left and right side. Post-order is left, right, root — the root appears at the last position. The policy is applied on each and every node (check only the three nodes: left child, right child, parent), not the entire tree at once. Tree reconstruction: using pre-order + in-order, or in-order + post-order, the entire tree structure can be recreated — instead of storing the actual tree structure, we can store two arrays and gain back the tree when required. Traversal is the basis for the stack procedures below and for the deletion-by-successor rule later.
Stack and stack-based traversal
A stack is a one-ended data structure where insertion and deletion are performed from the top, and the element on top is processed first (LIFO — last in, first out); it is compared to the chapati container at home, where the last chapati cooked is eaten first. Push is insertion into the stack; pop is deletion from the stack. A stack is used when we need to delay some operation over another. - Pre-order via stack: visit the root, then visit the left child and put the right child into the stack (not visiting it — removing all the right children and their sub-children into the stack). Visit B, then visit D and put the right child into the stack. On reaching the end, pick the first child from the stack — E — then next C. - Post-order via stack: target is left, right, root. Since access is via the root, if there is a left and right child, push the root into the stack, then if there is any right push it into the stack; reach B — B still has a child, so B is pushed; E is pushed; last D is pushed. D is the last element, so pop D, then pop E, then pop B, then pop C, then pop A. - In-order via stack: left, root, right. At the address of A, go to B; right and root are pushed into the stack; B's address (not B) is visited; when both fields are engaged, push the root and right child into the stack (right goes first, then root); then pop one by one to get back the series.
Binary tree and BST definitions
A binary tree is a tree where there are two possible movements in the lower direction — left child and right child; no condition is imposed on what goes left or right. A Binary Search Tree (BST) is a binary tree (maximum allowed children is two: zero, one, or two) in which each node n has the property: n is greater than every value in the left subtree and n is less than every value in the right subtree — in short left < root < right, with no equality sign, so duplicate entries are not allowed. Formal definition given: a binary search tree is always a binary tree; if each node n of the tree has the property that n is greater than every value on the left subtree and n is less than every value on the right subtree, it is a BST. BST is also known as a binary sorted tree — "sorted" means the same property is followed; binary search tree is the famous name. BSTs never allow duplicate entries; later trees (AVL, RB, MV, B tree) also never allow duplicates, B+ tree may allow duplicate entries, and heaps allow duplicates but have their own different property. A node in a BST may hold an entry record of the data — an array of values, not a single element (this relates to the MV tree); for explanation, single-element nodes are used. AVL, RB, MV and B trees all carry forward the BST property with something additional — BST is the base of the tree data structure.
The four primary operations and node types
The four primary operations in data structures are insertion, deletion, traversal, searching. Traversal and searching do not modify the tree structure, so the BST property is not hampered; insertion and deletion may violate the BST property and thus the property must be restored by certain operations (to be done later). Insertion rule: first search (since duplicates are not allowed); if not found, add the new element. Deletion rule: if found, remove; otherwise declare the element is not present. Three types of nodes: root (the initial point from where the tree primarily starts; also a special type of intermediate node), intermediate nodes (nodes having one or two children, not zero children), and leaf nodes (no children).
M-way search tree
An M-way search tree is a tree in which each node can contain multiple sorted keys; a node with M children is separated by at most M−1 keys (M pointers → M−1 separators), so a node holds at most M−1 keys — an order-4 M-way tree node holds at most 3 keys. Insertion of a new key generally begins by descending using the key ranges stored in each node until the target leaf is reached. In a full M-way tree of order 3 (root at level 0), level 3 holds at most $3^3 = 27$ nodes. In a B-tree of order 5 whose root holds keys 30 and 60, the middle child holds keys between 30 and 60.
Skewness problem
While constructing a BST, the tree may go skewed in one specific direction (few nodes on the left, increasing very high on the right). Inserting a, b, c, d, … gives a right-skewed tree; inserting z, y, x, …, a gives a left-skewed tree. It is no longer a tree but effectively a linear array, where searching takes order of n. This is the unbalancing problem: although left < root < right is maintained, the log n search time is not preserved, and the exercise of making the BST is lost because linear search would do the same. The fix is to maintain the BST to be of balanced height — left height and right height should not be exactly the same but should be comparable — so that log n can be preserved. This motivates the AVL tree.
AVL tree
The AVL tree (Adelson, Walensky, Landis) is the most popular balanced binary tree: a binary search tree with an additional condition that left and right heights are balanced. An empty binary tree is an AVL tree. The balance factor is the difference between left height and right height; AVL allows 0, 1 or −1 (not 2). For a leaf node the balance factor is 0. Rotations restore balance after insertion: inserting 30, 20, 10 (a left-left chain) needs a right rotation; inserting 10, 30, 20 (a left-right chain) needs an RL (right-left) rotation.
Deletion in a BST
- Case 1: node has no child — delete by replacing the location of the node in the parent by a null pointer.
- Case 2: node has exactly one child — delete by replacing the location by the one child.
- Case 3: node has two children — use the in-order successor (the next node in the in-order traversal). Some books/literature recommend the in-order predecessor instead; that is also allowed. Cormen usually follows in-order successor. Either way, the BST property is not hampered.
- In-order successor and predecessor defined: the in-order successor is the leftmost node of the right subtree; the in-order predecessor is the largest key in the left subtree, if that subtree exists.
- Why only these replacements: if you replace with any other node, the BST property (left less than root, root less than right) will change; using the in-order successor or predecessor keeps the structure of the tree intact. The ultimate aim is that after deletion or insertion the three properties are restored.
- Cascading: case 1 and case 2 may have cascading; case 0 (removing a node from the leaf, since it has no child) does not have cascading. Cascading means one removal requires another removal — e.g., to remove 50 you must remove 33, and to remove 33 you must remove 44.
- Pointer update on replacement (case 2): there is no swap of actual values — just the pointer starts pointing to the replacing node. E.g., when 66 replaces 75, the parent pointer of 75 starts pointing to 66; 75 becomes a node without any pointer address, i.e., a dangling pointer, and its location is marked empty.
- Zero child vs one child: zero child means both pointers are nil. One child means one root and one node that is left/right. To remove the root it becomes case two; to remove a leaf it becomes case one. Any leaf node is case one; an intermediate node with one child is case two; an intermediate node or root with two children is case three.
Memory/table representation and the avail pointer
The table is the memory; it holds addresses (the info part), and left and right are the links. E.g., "left 8" means at location 8 the left child is present; "right 10" means at location 10 the right child is present. 8 and 10 are addresses, not values — at address 8 you find 15, at address 10 you find 50. The avail pointer points to the available list; when a node is removed, the pointer shifts to that location; insertion and deletion happen from the top (where the node is started). This is an important property of avail.
Heaps and heap sort
A Min Heap always has the minimum element at the root. Heap Sort (Max Heap) guarantees $O(n \log n)$ in the worst case, which is its major advantage over Quick Sort. During Heap Sort, after swapping the root with the last element of the active heap, the reduced heap is heapified. Bottom-up heap construction on [4, 10, 3, 5, 1] gives the Max Heap [10, 5, 3, 4, 1]. Repeatedly removing the maximum and placing it at the end of the array produces ascending order. Heap Sort is not stable in general.
Formulas and maths
- Sequential representation policy: node at index $k$ has children at $2k$ and $2k+1$. $k$ is the node's array index; used to place a tree into a linear array.
- BST property: $\text{left} < \text{root} < \text{right}$ (no equality sign). Applies to every node n relative to every value in its left and right subtrees; used to define and validate a BST.
- Average BST search time: $O(\log n)$. $n$ is the number of elements; used to contrast BST search with the order of $n$ comparisons in a linear linked list or array.
- Insertion/deletion time: order of $\log n$ (search dominates) plus order of $1$ (adding/removing the node). $n$ is the number of elements; used when the tree is balanced — if the tree becomes skewed, order of $\log n$ reaches order of $n$.
- Cascading deletion complexity: $\log n$ plus some constant (e.g., "$\log n + 10$", "$\log n + 9$"). $n$ is the number of elements; used to note that cascading deletion is never exactly $\log n$ but more than that, while the order remains $\log n$.
- Balance factor: $\text{BF} = \text{HTL} - \text{HTR}$ (height of left subtree minus height of right subtree). HTL and HTR are the heights of the left and right subtrees; used to check the AVL condition.
- AVL condition: the difference should be less than 1, i.e., the balance factor must be $0$, $1$ or $-1$ (not $2$); a leaf node has balance factor $0$. Used to decide whether a BST node is balanced.
- Edges in a tree: $n - 1$ for $n$ nodes. Every node except the root has exactly one incoming edge; used for tree counting.
- Maximum nodes in a binary tree of height $h$: $2^{h+1} - 1$. Levels $0..h$ each hold $2^{\text{level}}$ nodes; check $h=0$: $2^1-1=1$.
- Minimum height for $n$ nodes: $\lceil \log_2(n+1) \rceil - 1$. A perfect tree of height 3 holds $2^4-1=15 \ge 12$ nodes, while height 2 holds only $7 < 12$, so 12 nodes need at least height 3.
- Keys in an M-way node: at most $M-1$. M children are separated by at most M−1 keys; order 4 gives 3 keys.
- Nodes at level $l$ of a full M-way tree of order $M$: $M^l$. Root at level 0; order 3 at level 3 gives $3^3 = 27$.
Worked examples
Building a BST from 2, 7, 3, 1, 31, 41, 29, 44, 47, 63
(No duplicates included, since a BST will not contain any.) - 2 is the first element → root. - 7 > 2 → goes right of 2. - 3 > 2, but 3 < 7 → placed on the left of 7. - 1 < 2 → placed on the left of 2. - 31 > 2 → right; > 7 → right; placed on the right of 7. - 41: entry point is always the root; 41 > 2 → right; > 7 → right; > 31 → right of 31. - 29: > 2 → right; > 7 → right; < 31 → left of 31. - 44 placed next, then 47 further, then 63 further, and 71 further. - Observation: very few nodes in the left direction, but the right direction increases very high — this is the skewness problem.
Property-check example
Nodes 38, 14, 23, 18, 8 on one side and 56, 45, 82, 70 on the other — 8 is on the left of 14; 23 and 18 on the right; 18 < 23 so it is placed on the left of 23; 70 is under 82 with 56 and 45. The property holds.
Alphabetical example
Harris, Cohen, Levis, Kell, Rubin, Brown, Green, Davis — alphabetically sorted names less than the root appear on the left, and the root is further less than the right ("less" means appearing prior in alphabetical order).
Insertion into a pre-existing tree
Tree contains 38, 14, 56, 23, 45, 82, 70, 18; insert 20, 40, 60, 50, 33, 55, 11: - 20: 38 → left to 14; 20 > 14 → right to 23; 20 < 23 → left to 18; no further node → insert 20 as the right child of 18. - 40: 38 → right to 56; 40 < 56 → left to 45; 40 < 45 → insert 40 on the left of 45. - 60: 38 → right to 56; 60 > 56 → right to 82; 60 < 82 → left to 70; 60 < 70 → insert 60 on the left of 70. - 33: 38 → left to 14; 33 > 14 → right to 23; 23 has no node on its right → insert 33 on the right of 23. - 55: 38 → right to 56; 55 < 56 → left to 45; 55 > 45 → insert 55 on the right of 45. - 11: 38 → left to 14; 11 < 14 → left to 8; no node with value 11 → insert 11 on the right of 8. - At no point is the BST property violated, and only unique elements are added.
Depth and comparisons
In the work example tree, the maximum depth is 4 (levels labeled 0, 1, 2, 3, 4), so the height of the tree is 4; the maximum number of comparisons for inserting a new node is of the order of 4 — the comparisons performed were 1, 2, 3, 4, 5, i.e., order of n plus 1 or so.
Memory/table example
Tree: 60, 25, 75, 15, 50, 66, 33, 44 arranged likewise. In memory: start node 60; its left is at location 2 (25) and right at location 7 (75). For 25, left is at location 8 (15) and right at location 10 (50). 15 has left only, no right. 33's left is located at 1; 44 is at location 9 and has no left side. The avail pointer points at the 5th location.
- Case 1 — remove 44: 44 was at location 9 and is easily removed; location 9 becomes empty and is added on top of the avail list; avail now points to location 9.
- Case 2 — remove 75: 75 has a left child, so it is case 2. 66 replaces 75. 75 is removed from location 7 and avail now points to location 7. Why avail = 7 when 66 replaces 75: 66 remains at its location; the parent pointer of 75 starts pointing to 66 (60's right child pointer now points to 66). There is no swap of actual values, just pointer changes; 75 becomes a node without any pointer address — a dangling pointer — and its location is marked empty.
- Case 3 — remove 25: 25 has both left and right children. In-order of the tree: 15, 25, 33, 44, 50, 60, 66, 75. The in-order successor of 25 is 33. 33 itself holds one node (44), so this is case 2 combined with case 3: 44 comes up, 33 goes up and replaces 25. Result: 33 in place of 25, 44 where 33 was, and the table changes accordingly. This is a cascading successor. For removal of 33, it has one child, so 44 replaces 33; 33 is stored in a temporary location and replaces 25. Resultant tree: 33 in place, 44 below. Two deletions — hence "cascading successor node."
- Cascading example: to remove 50 requires removing 33, and removing 33 requires removing 44 — so 50's deletion is not simple; it requires one, two, three
Deleting 70 with its in-order successor
Tree: root 50, left child 30, right child 70; 70 has children 60 and 80. Deleting 70 uses its in-order successor — the leftmost node of the right subtree of 70 — which is 80, so 80 replaces 70. The common mistake is to answer 60 by reading "successor" as "left child"; 60 is the left child of 70 and precedes 70 in in-order, so it is the predecessor, not the successor.
Post-order of an inserted BST
Inserting 50, 30, 70, 20, 40, 60, 80 into an empty BST gives the post-order traversal 20, 40, 30, 60, 80, 70, 50.
Key takeaways
- Link representation for sparse trees, sequential (array) representation for dense trees; the array policy is $k \to 2k, 2k+1$.
- Pre-order, in-order and post-order differ only in where the root is visited; each has a stack procedure, and two traversals are enough to rebuild the tree.
- BST property is left < root < right with no equality — duplicates are never allowed; BST is the base of AVL, RB, MV and B trees.
- Search is $O(\log n)$ only while the tree is balanced; skewness turns it into order of $n$, which is what AVL fixes with balance factors 0, 1, −1.
- Deletion has three cases; two children means replace with the in-order successor (or predecessor), which may cascade.
- In the table representation, deletion only moves pointers and pushes the freed location onto the
availlist — no values are swapped. - A tree of $n$ nodes has $n-1$ edges; a binary tree of height $h$ holds at most $2^{h+1}-1$ nodes, and $n$ nodes need height at least $\lceil \log_2(n+1) \rceil - 1$.
- An M-way node holds at most $M-1$ keys; insertion descends by key ranges to the target leaf.
- Heap Sort guarantees $O(n \log n)$ worst case, heapifies the reduced heap after each root swap, and is not stable; a Min Heap keeps the minimum at the root.
Glossary
- Link representation: tree stored as nodes with left, info and right fields.
- Sequential representation: tree stored in an array with children at $2k$ and $2k+1$.
- Avail pointer: pointer to the top of the available (freed) memory list.
- Pre-order / in-order / post-order: root-left-right / left-root-right / left-right-root.
- BST: binary tree with left < root < right at every node; also called binary sorted tree.
- In-order successor: leftmost node of a node's right subtree; the in-order predecessor is the largest key in its left subtree.
- Cascading deletion: a deletion that forces further deletions down the tree.
- Skewness: the tree degenerating into a linear chain, making search order of $n$.
- AVL tree: balanced BST whose balance factor (left height minus right height) is 0, 1 or −1.
- M-way search tree: tree whose nodes hold multiple sorted keys, at most $M-1$ per node.
- Complete binary tree: all levels full except possibly the last, which fills from left to right.
- Heap: tree with the heap property; a Min Heap keeps the minimum at the root.