

















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


















Exam
Review: Binary Search Trees
■ key : an identifying field inducing a total ordering ■ left : pointer to a left child (may be NULL) ■ right : pointer to a right child (may be NULL) ■ p : pointer to a parent node (NULL for root)
Review: Binary Search Trees
key[leftSubtree(x)] ≤ key[x] ≤ key[rightSubtree(x)]
Inorder Tree Walk
Operations on BSTs: Search
TreeSearch(x, k) if (x = NULL or k = key[x]) return x; if (k < key[x]) return TreeSearch(left[x], k); else return TreeSearch(right[x], k);
Operations on BSTs: Search
TreeSearch(x, k) while (x != NULL and k != key[x]) if (k < key[x]) x = left[x]; else x = right[x]; return x;
Operations of BSTs: Insert
■ Like the search procedure above ■ Insert x in place of NULL ■ Use a “trailing pointer” to keep track of where you came from (like inserting into singly linked list)
BST Search/Insert: Running Time
■ We’ll keep all analysis in terms of h for now ■ Later we’ll see how to maintain h = O(lg n )
Sorting With Binary Search Trees
BSTSort(A) for i=1 to n TreeInsert(A[i]); InorderTreeWalk(root);
● Argue that this is Ω (n lg n)
■ Worst case? ■ Average case? (hint: remind you of anything?)
Sorting with BSTs
■ In previous example ○ Everything was compared to 3 once ○ Then those items < 3 were compared to 1 once ○ Etc. ■ Same comparisons as quicksort, different order! ○ Example: consider inserting 5
Sorting with BSTs
More BST Operations
■ Insert ■ Minimum ■ Extract-Min
BST Operations: Minimum