Understanding the Problem
We are given a Binary Search Tree (BST), and the goal is to flatten it into a sorted list.
That means we want to convert the hierarchical structure of the BST into a simple array that contains all the node values in increasing order.
Why does this work well with a BST? Because a BST has a special property: for every node, all values in the left subtree are smaller, and all values in the right subtree are greater.
So, if we perform an in-order traversal (Left → Node → Right), we naturally visit the nodes in ascending order.
Step-by-Step Solution with Example
step 1: Choose a suitable traversal
We need a way to visit all nodes in increasing order. The best traversal for this is in-order traversal, which processes the left subtree, then the current node, and then the right subtree.
step 2: Understand how in-order traversal behaves on a BST
Let's take an example BST:
5
/ 3 7
/ 2 4 9
The in-order traversal for this tree will visit the nodes in this order: 2, 3, 4, 5, 7, 9
. This is exactly the sorted order we want.
step 3: Implement a recursive in-order traversal
We'll use a helper function that traverses the tree in in-order fashion and appends each node's value to a result list.
step 4: Combine the results into a single sorted list
After the traversal is complete, the result list will contain all values in sorted order. This becomes our flattened version of the BST.
Edge Cases
Empty Tree
If the BST is null
or empty, we simply return an empty list: []
. There are no nodes to process.
Single-node Tree
If the tree contains only one node, say 5
, then the result list will be [5]
. The traversal works correctly even in this minimal case.
Left-skewed Tree
Consider a tree where every node only has a left child, like this:
4
/
3
/
2
The in-order traversal would be: 2, 3, 4
. Still sorted — no special handling needed.
Right-skewed Tree
For a tree where each node has only a right child:
1
2
3
The in-order traversal gives: 1, 2, 3
, again correctly sorted.
Finally
Flattening a BST into a sorted list becomes straightforward once we recognize the power of in-order traversal.
It leverages the inherent structure of the BST to extract elements in order without any additional sorting steps.
By carefully handling edge cases like empty trees or skewed trees, we ensure the solution is robust and beginner-friendly.
This technique is efficient and commonly used in many coding interviews and real-world systems where sorted access to tree data is required.
Comments
Loading comments...