Professional Documents
Culture Documents
Tree Traversal Concept Tree Traversal Techniques: Preorder, Inorder, Postorder Full Trees Almost Complete Trees Heaps
CS 103 1
7 9 10 12
CS 103
Preorder Traversal: 1. Visit the root 2. Traverse left subtree 3. Traverse right subtree Inorder Traversal: 1. Traverse left subtree 2. Visit the root 3. Traverse right subtree Postorder Traversal: 1. Traverse left subtree 2. Traverse right subtree 3. Visit the root
7
1 3 5 6 11 8 7 9 10 12
15 8 2 11 6 10 12 3 7 20 27 22 30 14
CS 103
12
CS 103
13
8 9 10 111213 14 15
1 2 2 4
1 3 2 4 5 2 1 3 4
3 5 6
2 4
15
CS 103
16
15 1
11 30 27 13 6 10 12 5 6 7 8 9 10 11
Notice: Left child of A[5] (of data 11) is A[2*5]=A[10] (of data 18), and its right child is A[2*5+1]=A[11] (of data 12). Parent of A[4] is A[4/2]=A[2], and parent of A[5]=A[5/2]=A[2]
CS 103 19
Adjustment of Indexes
Notice that in the previous slides, the node labels start from 1, and so would the corresponding arrays But in C/C++, array indices start from 0 The best way to handle the mismatch is to adjust the canonical labeling of full and almost complete trees. Start the node labeling from 0 (rather than 1). The children of node k are now nodes (2k+1) and (2k+2), and the parent of node k is (k-1)/2, integer division.
CS 103 20
Example of a Min-heap
5 8 15 33 16 18 11 12 20 30 27
CS 103
22
Operations on Heaps
Delete the minimum value and return it. This operation is called deleteMin. Insert a new data value
Applications of Heaps: A heap implements a priority queue, which is a queue that orders entities not a on first-come first-serve basis, but on a priority basis: the item of highest priority is at the head, and the item of the lowest priority is at the tail Another application: sorting, which will be seen later
CS 103 23
DeleteMin in Min-heaps
The minimum value in a min-heap is at the root! To delete the min, you cant just remove the data value of the root, because every node must hold a key Instead, take the last node from the heap, move its key to the root, and delete that last node But now, the tree is no longer a heap (still almost complete, but the root key value may no longer be the keys of its children
CS 103 24
8 15 16 18 11 12
20 30 27
16 18 12 12 8 15
12 8 15 16 18
25
20 11 30 27
33
16 18
Restore Heap
To bring the structure back to its heapness, we restore the heap Swap the new root key with the smaller child. Now the potential bug is at the one level down. If it is not already the keys of its
children, swap it with its smaller child Keep repeating the last step until the bug key becomes its children, or the it becomes a leaf
CS 103 26
Illustration of Restore-Heap
12 8 15 33 16 18 8 11 15 33 16 18 12 20 30 27 Now it is a correct heap
CS 103 27
8 20 12 27 33 15 16 18 11 20 30 27 30
11
But the height is O(log n) Therefore, both insert and deletemin take O(log n) time, which is very fast.
CS 103 28
CS 103
30
CS 103
34