Which reason best explains why a Binary Search Tree (BST) might be preferred over a Hash Map when working with ordered data?
Think about how each structure stores and accesses data in order.
BSTs keep data sorted by design, enabling ordered operations like range queries and sorted traversal. Hash Maps do not maintain order.
Given the following data inserted into a BST and a Hash Map, what is the output of an in-order traversal of the BST and the list of keys from the Hash Map?
data = [50, 30, 70, 20, 40, 60, 80] # BST in-order traversal output # Hash Map keys output (order not guaranteed)
Recall that BST in-order traversal visits nodes from smallest to largest.
In-order traversal of BST visits nodes in ascending order. Hash Map keys have no guaranteed order.
Consider this simplified BST insertion code snippet. Why does it fail to keep the tree ordered?
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def insert(root, val):
if root is None:
return Node(val)
if val > root.val:
root.left = insert(root.left, val)
else:
root.right = insert(root.right, val)
return rootCheck which subtree the greater values are inserted into.
In a BST, values greater than the current node go to the right subtree, but here they are inserted into the left subtree, breaking order.
You need to frequently find all keys between two values in a large dataset. Which data structure is best suited for this task?
Think about which structure keeps data sorted and allows sequential access.
BSTs keep data sorted and allow efficient range queries by traversing nodes between two values. Hash Maps do not maintain order, so range queries are inefficient.
Given the following operations, what is the final printed output?
class BSTNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def insert(root, val):
if root is None:
return BSTNode(val)
if val < root.val:
root.left = insert(root.left, val)
else:
root.right = insert(root.right, val)
return root
def inorder(root, result):
if root:
inorder(root.left, result)
result.append(root.val)
inorder(root.right, result)
# Insert into BST
root = None
for v in [40, 20, 60, 10, 30, 50, 70]:
root = insert(root, v)
# Create Hash Map
hmap = {}
for v in [40, 20, 60, 10, 30, 50, 70]:
hmap[v] = v * 2
# Remove key 60 from Hash Map
hmap.pop(60)
# Print BST in-order
bst_result = []
inorder(root, bst_result)
print('BST:', ' -> '.join(map(str, bst_result)) + ' -> null')
# Print Hash Map keys sorted
print('Hash Map keys:', sorted(hmap.keys()))Trace the BST insertion and Hash Map removal carefully.
The BST in-order traversal prints all inserted values in ascending order. The Hash Map has key 60 removed, so it is missing from the keys list.
