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.
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.
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.
[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).