Week 10 Tutorial Notes

Heaps and Tries

Group Question

  1. You are given the following array representation of a min heap as a starting point.
  2. Index 0 1 2 3 4 5 6 7 8 9
    Value - 1 3 2 10 5 5 9 12 -

    1. Delete once from the heap and write the array representation.
    2. Use the heap state from \((a)\) and insert the value \(1\). Write the tree representation.

  3. Consider this trie. Terminating nodes are marked in dotted red.


    1. How many words are in the trie?
    2. How many nodes need to be removed to delete the following words from the trie:
      • Snow
      • Leopard
      • Jump
      • Snout
      • Leo
    3. How many new nodes need to be added to insert the following words into the trie:
      • Leon
      • Jest
      • Snobbish
      • Kayak

    Revision Question

  4. What is the Time Complexity of funcA function?
  5. void funcA(int *arr, int size, int i) {
        while (i > 1 && arr[i] > arr[i / 2]) {
            int tmp = arr[i];
            arr[i] = arr[i / 2];
            arr[i / 2] = tmp;
            i = i / 2;
        }
    }
    

    1. Give a use case for performing a Post Order Traversal on a Binary Search Tree.
    2. Write Pseudocode for it.
  6. What are two major differences between Selection Sort and Merge Sort?
  7. Explain the main difference between a Binary Search Tree and AVL Tree?


  8. Group Work Answers:

    Click each section to reveal.

    1. Array Representation after removing an element.
      Index 0 1 2 3 4 5 6 7 8 9
      Value - 2 3 5 10 5 12 9 10 -
    2. Tree Representation after inserting \(1\).

    1. There are 10 words in the trie.
      • Unmark W. 0 nodes removed.
      • 4 nodes removed. P, A, R, D.
      • 4 nodes removed. J, U, M, P.
      • 2 nodes removed. U, T.
      • Unmark O. 0 nodes removed.
      • Mark N red. 0 nodes added.
      • 3 nodes added. E, S, T.
      • 4 nodes added. B, I, S, H.
      • 5 nodes added. K, A, Y, A, K.

    This function has a Time Complexity of \(O(\log(n))\). The function is halving \(i\) for each iteration. (Note: This logic is used to perform FixUp for Max heaps)

    1. Deleting all the nodes in a Binary Search Tree.
    2. void postFix(struct node *tree) {
          if (tree == NULL) return;
          postFix(tree->left);
          postFix(tree->right);
          free(tree);
          return;
      }
      

      Selection Sort is unstable sorting algorithm and is \(O(n^2)\). Whereas Merge Sort is a stable sorting algorithm and \(O(n\log(n))\).

      AVL Trees are always height balanced by construction which makes searching \(O(\log(n))\). Whereas a BST is not guranteed to be height balanced, so the height in the worst case is \(O(n)\).