Data Structures and Algorithms
When a binary search tree is traversed in in-order (visiting the left subtree, then the node, then the right subtree), how are the values of the visited nodes ordered? Assume all values are distinct.
- AIn ascending order (smallest first)
- BIn the order they were inserted
- CIn order of closeness to the root (shallowest first)
Show answer and explanation
Answer: A. In ascending order (smallest first)
In a binary search tree, for every node, all values in the left subtree are smaller than the node and all values in the right subtree are larger. Visiting the left subtree, the node and then the right subtree therefore visits the values from smallest to largest, so the result is in ascending order. Visiting nodes in order of closeness to the root is a breadth-first (level-order) traversal, which goes level by level from left to right. The insertion order affects the shape of the tree but does not match the order of any of these traversals.
- A. Correct. Since the left side is smaller and the right side larger, in-order traversal gives ascending order.
- B. The insertion order affects the tree's shape, but in-order traversal gives ascending order regardless of it.
- C. This is the result of a breadth-first (level-order) traversal, which visits the tree level by level.