There are several approaches to flatten a Binary Search Tree (BST) into a linked list. I'll explain the most common method that converts the BST into a right-skewed tree (where each node only has a right child), effectively creating a linked list structure.
Problem Understanding
When flattening a BST into a linked list, we typically want to maintain the in-order traversal sequence. For a BST, this means the resulting linked list will be sorted in ascending order.
Approach 1: Using In-Order Traversal with Array
The straightforward approach involves collecting all nodes during in-order traversal, then reconstructing the tree:
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def flatten_bst_with_array(root):
if not root:
return None
# Step 1: Collect nodes in in-order sequence
nodes = []
def inorder(node):
if node:
inorder(node.left)
nodes.append(node)
inorder(node.right)
inorder(root)
# Step 2: Reconstruct as right-skewed tree
for i in range(len(nodes)):
nodes[i].left = None
nodes[i].right = nodes[i + 1] if i + 1 < len(nodes) else None
return nodes[0] if nodes else None
Approach 2: Morris Traversal (Space-Efficient)
This approach modifies the tree structure during traversal without using extra space:
def flatten_bst_morris(root):
if not root:
return None
current = root
while current:
if current.left:
# Find the rightmost node in left subtree
predecessor = current.left
while predecessor.right and predecessor.right != current:
predecessor = predecessor.right
if not predecessor.right:
# Create temporary link
predecessor.right = current
current = current.left
else:
# Remove temporary link and process
predecessor.right = None
# Move current's left subtree to right
temp = current.right
current.right = current.left
current.left = None
# Find the end of the moved subtree
while current.right:
current = current.right
# Attach the original right subtree
current.right = temp
current = temp
else:
current = current.right
return root
Approach 3: Recursive with Previous Node Tracking
This elegant recursive solution maintains a reference to the previously processed node:
def flatten_bst_recursive(root):
def flatten_helper(node, prev):
if not node:
return prev
# Process right subtree first (reverse in-order)
prev = flatten_helper(node.right, prev)
# Process current node
node.right = prev
node.left = None
prev = node
# Process left subtree
prev = flatten_helper(node.left, prev)
return prev
flatten_helper(root, None)
return root
Approach 4: Iterative with Stack
Using a stack to simulate the recursive process:
def flatten_bst_iterative(root):
if not root:
return None
stack = [root]
prev = None
while stack:
current = stack.pop()
# Push right child first, then left (for correct order)
if current.right:
stack.append(current.right)
if current.left:
stack.append(current.left)
# Connect to previous node
if prev:
prev.left = None
prev.right = current
prev = current
return root
Time and Space Complexity Analysis
Array Approach:
- Time: O(n) for traversal + O(n) for reconstruction = O(n)
- Space: O(n) for storing nodes + O(h) for recursion = O(n)
Morris Traversal:
- Time: O(n) - each edge traversed at most twice
- Space: O(1) - no additional space except variables
Recursive Approach:
- Time: O(n) - visit each node once
- Space: O(h) - recursion stack depth, where h is tree height
Iterative Approach:
- Time: O(n) - visit each node once
- Space: O(h) - stack space for tree height
Example Walkthrough
Consider this BST:
4
/ \
2 6
/ \ / \
1 3 5 7
After flattening, it becomes:
1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7
Represented as a right-skewed tree:
1
\
2
\
3
\
4
\
5
\
6
\
7
The Morris traversal approach is often preferred for its constant space complexity, while the recursive approach is more intuitive and easier to understand. Choose based on your specific constraints regarding space usage and code readability.