1. Basic Concepts
- Tree is a nonlinear/nonsequential data structure where nodes are organized in a hierarchical way.
- Some preliminaries:
- depth (level) of a node -- length of the path from the root to the node
- height of a node -- length of the path from the node to the deepest node in the tree
- height of a tree -- height of the root
Definitions on the nodes in a tree
- leaf node -- a node with no children
- internal node -- any node in a tree that is not a leaf
2. Binary Trees
- Binary tree is a special kind of tree in which nodes have at most 2 children (none or left-child only or right-child or both).
- When a tree of height d has all nodes filled from level 0 to d-1, and the leaf nodes at the dth level are filled from the left-most position, then the tree is called a complete binary tree.
![]()
- If every node in a binary tree has either 2 children or 0, then the tree is called a full binary tree.
3. Mathematical Properties of binary trees
- Number of nodes on each level i is at most 2i
- level 0: 20 = 1 ... root
- level 1: 21 = 2
- level 2: 22 = 4
Those are upper bound numbers which hold when a tree is fully expanded (i.e., a tree of depth d is complete and all nodes at depth 0 through d-1 have two children).
- Total number of nodes in a (general) binary tree of depth d is
- upper bound: 20 + 21 + 22 + .. + 2d = 2d+1 -1 (by geometric sequence) -- when a tree is fully expanded
- lower bound: d + 1 -- when all internal nodes have 1 child (called a degenerate tree)
- Depth (or height) of a binary tree with N nodes >= floor(lgN)
- lower bound: floor(lgN) .. when a tree is fully expanded
- upper bounf: N - 1 .. , when a tree is a degenerate tree
e.g. floor(lg31) = 4
EXERCISES:
- How many nodes are in a fully expanded binary tree of depth 5? Of them, how many are internal, and how many are leaf nodes?
- What is the depth of a complete binary tree with 200 nodes?
EXERCISE: Assume that the array representing a min binary heap contains the values 2, 8, 3, 10, 16, 7, 18, 13. Show the contents of the array after inserting the value 4.
EXERCISE: Assume that the array representing a min binary heap contains the values 2, 8, 3, 10, 16, 7, 18, 13. Show the contents of the array after deleting the minimum element.
Steps:
Final result:
EXERCISE: Show the array representing the min binary heap constructed using the initial values 18, 2, 13, 10, 15, 3, 7, 16, 8.
Before processing, if a heap H is a min-heap, change it to a max-heap. 1. Build-Heap(H). 2. For i = length[H]-1 downto 1 3. Swap(H[0], H[i]). 4. percDown(H, 0, i). // range between H[0] to H[i]
EXERCISE: Given an array [17, 23, 10, 1, 7, 16, 9, 20], sort it on paper using heapsort. Write down explicitly each step.