Of course! Here is a detailed, step-by-step explanation of how to flatten a Binary Search Tree (BST) into a Linked List.
1. Understanding the Goal
First, let's clarify what "flattening a BST into a Linked List" means.
You start with: A Binary Search Tree. This is a tree data structure where for each node, all values in its left subtree are smaller, and all values in its right subtree are larger.
You want to end up with: A structure that behaves like a Linked List, where each node points only to the next node in the sequence. The key requirement is that this "linked list" must be sorted in ascending order.
The Transformation: We will reuse the existing tree nodes. The final structure will use the right pointer of each node to point to the next node in the sorted list, and the left pointer of every node will be set to NULL.
Example:
Before (BST):
code
4
/ \
2 6
/ \ / \
1 3 5 7
After (Linked List):
code
1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> NULL
Notice that the nodes in the final list are sorted, which is the natural result of an in-order traversal of the original BST. This insight is the key to solving the problem.
Key Insight: In-Order Traversal
The foundation of this problem is the in-order traversal of a BST. An in-order traversal visits nodes in the following order:
Recursively visit the left subtree.
Process the current node.
Recursively visit the right subtree.
When you perform an in-order traversal on a BST, you visit the nodes in their natural sorted order (1, 2, 3, 4, 5, 6, 7 in our example). Our goal is to simply "capture" this order and rewire the pointers as we go.
We will explore two main approaches:
Approach 1: Using Extra Space (Intuitive) - Simple to understand and implement.
Approach 2: In-Place Modification (Optimal) - More complex but space-efficient.
Approach 1: Using Extra Space (The Simple Method)
This is the most straightforward way to think about the problem. The idea is to first get all the nodes in the correct order and then build the linked list from that ordered collection.
Algorithm:
Create a temporary list/array: Initialize an empty list (like a Python list or a std::vector in C++).
Perform In-Order Traversal: Traverse the BST using an in-order traversal. In the "visit" step, instead of printing the node's value, add the node object itself to your temporary list.
Rewire the Pointers: After the traversal is complete, your list contains all the BST nodes, sorted correctly. Iterate through this list from the first to the second-to-last element. For each node at index i:
Set node[i].right = node[i+1] (point its right child to the next node in the list).
Set node[i].left = NULL (clear its left child).
Finalize the List: For the very last node in the list, set both its left and right pointers to NULL.
Return the Head: The head of your new linked list is the first element of your temporary list.
Visualizing the Steps:
BST:[4, 2, 6, 1, 3, 5, 7]
In-Order Traversal & Store Nodes:
Visit left of 4 -> 2
Visit left of 2 -> 1. Add Node(1) to list. List: [Node(1)]
Visit 2. Add Node(2). List: [Node(1), Node(2)]
Visit right of 2 -> 3. Add Node(3). List: [Node(1), Node(2), Node(3)]
... and so on.
Final List of Nodes:[Node(1), Node(2), Node(3), Node(4), Node(5), Node(6), Node(7)]
Rewire Pointers:
Node(1).right = Node(2), Node(1).left = NULL
Node(2).right = Node(3), Node(2).left = NULL
...
Node(6).right = Node(7), Node(6).left = NULL
Node(7).right = NULL, Node(7).left = NULL
Code Example (Python):
python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def flatten_bst_extra_space(root: TreeNode) -> TreeNode:
if not root:
return None
# Step 1: Create a list to store nodes
sorted_nodes = []
# Step 2: Perform in-order traversal
def inorder_traversal(node):
if not node:
return
inorder_traversal(node.left)
sorted_nodes.append(node) # Add the node object
inorder_traversal(node.right)
inorder_traversal(root)
# Step 3 & 4: Rewire the pointers
for i in range(len(sorted_nodes) - 1):
# Point right pointer to the next node in the list
sorted_nodes[i].right = sorted_nodes[i+1]
# Set left pointer to None
sorted_nodes[i].left = None
# Handle the last node
last_node = sorted_nodes[-1]
last_node.left = None
last_node.right = None
# Step 5: Return the new head (the first node)
return sorted_nodes[0]
Complexity Analysis:
Time Complexity: O(N), where N is the number of nodes. We visit each node once for the traversal and once for the rewiring.
Space Complexity: O(N). We create an auxiliary list that stores all N nodes.
Approach 2: In-Place Modification (The Optimal Method)
This approach is more efficient in terms of space. We modify the tree while we are traversing it, avoiding the need for an O(N) auxiliary data structure. The trick is to keep track of the previously visited node during the traversal.
We will use a clever variation of the in-order traversal: the Reverse In-Order Traversal (Right, Visit, Left). This is often easier to implement for this problem.
Algorithm (Reverse In-Order):
The core idea is to build the list from tail to head. We traverse the tree from the largest element to the smallest. We keep a prev (or head) pointer that tracks the head of the already-flattened list (which will be the largest element we've processed so far).
Initialize a pointer: Create a pointer, let's call it prev, and initialize it to NULL. This prev will always point to the head of the "linked list" we have built so far.
Perform Reverse In-Order Traversal: Create a recursive function that takes a node as input.
Base Case: If node is NULL, just return.
Recurse Right: First, call the function on the node.right child. This will process the entire right subtree, building a sorted list from its elements. After this call, prev will point to the smallest element in that right subtree (which is now the head of its own flattened list).
Process Current Node (The "Visit" Step):
Set node.right = prev. This links the current node to the head of the list we just built from the right subtree.
Set node.left = NULL.
Update prev = node. The current node is now the new head of our growing linked list.
Recurse Left: Finally, call the function on the node.left child. This will continue the process, prepending the elements from the left subtree to the list we've built.
Return the Head: After the initial call on the root node completes, the prev pointer will be pointing to the overall head of the final flattened list (the smallest element in the entire tree).
Visualizing the Reverse In-Order Steps:
Let's trace flatten(node) with prev as a global or passed-by-reference pointer, initially NULL.
Start with flatten(4).
flatten(4) calls flatten(6).
flatten(6) calls flatten(7).
flatten(7) calls flatten(null) (right of 7). Returns.
Process Node 7:
node(7).right = prev (which is NULL).
node(7).left = NULL.
prev = node(7). (List so far: 7 -> NULL)
flatten(7) calls flatten(null) (left of 7). Returns. flatten(7) is done.
Back in flatten(6). Process Node 6:
node(6).right = prev (which is node(7)).
node(6).left = NULL.
prev = node(6). (List so far: 6 -> 7 -> NULL)
flatten(6) calls flatten(5).
flatten(5) processes itself, setting node(5).right = prev (which is node(6)) and prev becomes node(5). (List so far: 5 -> 6 -> 7 -> NULL)
...and so on. The process continues, always prepending the current node to the front of the list pointed to by prev. The final value of prev will be node(1).
Code Example (Python):
python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def __init__(self):
# This pointer will track the head of the already-processed list
self.prev = None
def flatten_bst_in_place(self, root: TreeNode) -> TreeNode:
self.reverse_inorder_and_relink(root)
return self.prev
def reverse_inorder_and_relink(self, node: TreeNode):
# Base case
if not node:
return
# 1. Recurse on the right subtree
self.reverse_inorder_and_relink(node.right)
# 2. Process the current node
node.right = self.prev # Link current node to the list built so far
node.left = None # Nullify the left pointer
self.prev = node # Current node becomes the new head of the list
# 3. Recurse on the left subtree
self.reverse_inorder_and_relink(node.left)
# --- How to use it ---
# bst_root = ... (your BST root)
# solver = Solution()
# linked_list_head = solver.flatten_bst_in_place(bst_root)
Complexity Analysis:
Time Complexity: O(N). Each node is visited exactly once.
Space Complexity: O(H), where H is the height of the tree. This space is used by the recursion call stack.
For a balanced BST, H is approximately log(N), so the space is O(log N).
For a skewed, unbalanced tree (which already looks like a linked list), H is N, so the space is O(N) in the worst case. This is still better than the guaranteed O(N) extra space of Approach 1.
Summary and Comparison
Feature
Approach 1: Extra Space
Approach 2: In-Place Modification
Time Complexity
O(N)
O(N)
Space Complexity
O(N) (for the auxiliary list)
O(H) (for the recursion stack)
Implementation
Simpler, more intuitive
More complex, requires careful thought
Modification
Modifies the tree after traversal
Modifies the tree during traversal
Which one should you use?
For an interview: The interviewer is almost always looking for the in-place (Approach 2) solution. It demonstrates a deeper understanding of recursion and pointer manipulation.
For quick, practical code: If memory is not a concern and you need a simple, readable solution, Approach 1 is perfectly fine and less prone to bugs.