Which of the following is the main reason to prefer a Binary Search Tree (BST) over a Hash Map when you need to maintain ordered data?
Think about how data is stored and accessed in both structures.
BSTs store data in a sorted manner, so traversing them in order gives sorted data. 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 keys of the Hash Map?
int[] values = {5, 3, 7, 2, 4}; // Insert into BST and Hash Map // In-order traversal of BST prints keys in ascending order // Hash Map keys printed in insertion order or arbitrary order depending on implementation
Remember how BST in-order traversal works and how Hash Map keys are stored.
BST in-order traversal visits nodes in ascending order. Hash Map keys do not guarantee order and often reflect insertion order or arbitrary order.
Consider this C# method for a BST range query that should return all keys between low and high in sorted order. Why does it fail?
void RangeQuery(Node root, int low, int high, List<int> result) { if (root == null) return; if (root.Key >= low && root.Key <= high) result.Add(root.Key); if (root.Key > low) RangeQuery(root.Left, low, high, result); if (root.Key < high) RangeQuery(root.Right, low, high, result); }
Think about the order nodes are visited in an in-order traversal.
Adding the root key before traversing the left subtree breaks the sorted order. In-order traversal visits left subtree, then root, then right subtree.
Which option correctly fixes the syntax error in this C# BST insertion snippet?
Node Insert(Node root, int key) { if (root == null) { return new Node(key); } if (key < root.Key) { root.Left = Insert(root.Left, key); } else { root.Right = Insert(root.Right, key); } return root; }
Look carefully at line endings in C#.
C# requires semicolons at the end of statements. Missing semicolon causes syntax error.
You need to store a large set of integer keys with frequent insertions and perform many range queries that return keys in sorted order. Which data structure is best and why?
Consider the cost of maintaining order and performing range queries efficiently.
Self-balancing BSTs keep data sorted dynamically, allowing fast insertions and efficient range queries. Hash Maps do not maintain order, arrays require costly sorting after inserts, and linked lists do not support fast searches.
