VOOZH about

URL: https://www.geeksforgeeks.org/dsa/flatten-bst-to-sorted-list-increasing-order/

⇱ Flatten BST to sorted list | Increasing order - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Flatten BST to sorted list | Increasing order

Last Updated : 11 Oct, 2025

Given the root of a Binary Search Tree. Flatten the BST into a sorted linked list.
Note: Flattening a BST means: Every node’s left child should be null and the right child points to the next node in sorted order. In other words, after flattening, the BST should behave like a singly linked list that follows the increasing order of node values.

Examples:

Input:

πŸ‘ 420046826

Output: [[2],[N, 3], [N, 4], [N, 5], [N, 6], [N, 7], [N, 8]]
Explanation: After flattening, the BST becomes a right-skewed tree where all nodes follow the sorted order like a linked list.

πŸ‘ 420046827

Input:

πŸ‘ 420046825


Output: [[1]], [N, 2], [N, 3], [N, 4], [N, 5]]
Explanation: After flattening, the BST becomes a right-skewed tree where all nodes follow the sorted order like a linked list.

πŸ‘ 420046825

[Naive Approach] By Storing Inorder Traversal - O(n) Time and O(n) Space

The approach is to traverse the BST in inorder to obtain the nodes in ascending order. Using this sequence, we rebuild the tree so that each node has no left child, and its right child points to the next node in the sorted list, resulting in a right-skewed tree.


Output
2 
N 3 
N 4 
N 5 
N 6 
N 7 
N 8 

[Expected Approach] Using Single Traversal - O(n) Time and O(n) Space

The idea is to traverse the BST in inorder to maintain the sorted order. We maintain a dummy node with value -1 and a prev pointer initially pointing to this dummy node, representing the last processed node. For each node, we set its left child to null, link the previous node’s right child to the current node, and update prev to the current node, repeating this process for all nodes to create a right-skewed linked list in increasing order.

Pseudo- Code Idea:

  • if curr is equal to null return.
  • Recursive call for left subtree - flatten(curr -> left, prev).
  • set pre -> left = NULL, pre -> right = curr and pre = curr.
  • Recursive call for right subtree - flatten(curr -> right, prev).

Output
2 
N 3 
N 4 
N 5 
N 6 
N 7 
N 8 
Comment
Article Tags:
Article Tags: