To solve this problem, we need to flatten a Binary Search Tree (BST) into a sorted list. The most efficient way to achieve this is by performing an in-order traversal, which visits nodes in sorted order due to the properties of BSTs.
Case 1: Standard BST
For a typical BST with multiple nodes, an in-order traversal will visit the left subtree, then the current node, and finally the right subtree.
We recursively collect values in this order, which guarantees a sorted list as output.
Case 2: Tree with only left or right children
If the BST has only left children (e.g., a descending linked list), the traversal still works, collecting values from left to right.
If the BST has only right children (e.g., an ascending linked list), the in-order traversal collects values in the same order as they appear.
Case 3: Single-node tree
If the BST consists of just a single node, the sorted list will contain only that node’s value.
This is a valid scenario and should return a list with one element.
Case 4: Empty tree
If the BST is empty (i.e., the root is null
), we return an []
— an empty list — since there are no elements to collect.
Approach Summary
We use a recursive in-order traversal approach that:
- Traverses the left subtree first
- Appends the current node's value
- Traverses the right subtree
This approach is efficient and leverages the natural ordering of BSTs.