Ordered Map and BST Flashcards
What is an Ordered Map
Similar to a map, but with the keys being ordered.
2 Implementations of Ordered Map
- Array -> very inefficient
- Binary Search Tree
What is the BST Property
Everything to the left of a vertex has a smaller value. Everything to the right of a vertex has a greater or equal value to the vertex. Unlike min / max heap.
3 Implementations of BST
- Sequential Array (inefficient)
- Parent Array (inefficient)
- Nodes (best)
Time Complexity of Search
O(h) -> Not the same as O(logn) because BST is unlikely to be a perfect tree. If current node value too large, search from left child, else search from right child.
Time Complexity of Insertion
O(h) -> Same logic as in search, insert the node at the right place and recursively assign the node as the appropriate child.
Time Complexity of GetMax
O(h) -> Recursively visit the right child until you reach a node with no right child, then return the node’s value.
Time Complexity of GetMin
O(h) -> Recursively visit the left child until you reach a node with no left child, then return that node’s value.
Time Complexity of Successor
O(h) -> If the node with value x has a right child, the minimum of the right subtree is the successor. If it doesn’t, keep going up until it finds a parent a that is the left child of parent b. Return parent b’s value.
Time Complexity of Predecessor
O(h) -> If the node with value x has a left child, the maximum of the left subtree is the predecessor. If it doesn’t, keep going up until it finds a parent a that is the right child of parent b. Return parent b’s value.
Time Complexity of ListSorted
O(3n) = O(n) -> Do in-order traversal: If the current node is null, return. Else visit the left child. Process the current node value. Visit the right child. 3n because you visit each node 3 times.
Time Complexity of Deletion
Overall O(h)
- Vertex v has no children -> O(1): Just remove v
- Vertex v has 1 child -> O(1): Connect child to parent.
- Vertex v has 2 children -> O(h): Find the successor x of v. Replace v.key with x.key. Recursively delete x in v.right.
Time Complexity of Rank
O(h) -> Check if value is smaller, larger, equal to value of current node. If smaller, recursively return rank(curr.left). If equal, return curr.left.size + 1. If larger, return curr.left.size + 1 + rank(curr.right).
Time Complexity of Select -> given a rank, return the value of the node with that rank
O(h) -> Check if rank needed is smaller than rank of current node (curr.left.size + 1), equal or larger. If equal, return the current node’s value. If smaller, recursively call with curr.left and rank k. If larger, recursively call with curr.right and rank (k - rank(curr))What
What is the worst case for a BST
When height = N. To prevent this, we use AVL trees.