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
Try It Yourself
redirect icon

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

C++
//Driver Code Starts
#include <iostream>
#include <vector>
#include<queue>
using namespace std;

// Node structure
struct Node {
    int data;
    Node* left;
    Node* right;
    Node(int data) {
        this->data = data;
        left = right = nullptr;
    }
};

// Calculate Height
int getHeight(Node* root, int h) {
    if (root == nullptr) return h - 1;
    return max(getHeight(root->left, h + 1), getHeight(root->right, h + 1));
}

// Print Level Order
void levelOrder(Node* root) {
    queue<pair<Node*, int>> q;
    q.push({root, 0});

    int lastLevel = 0;

    // function to get the height of tree
    int height = getHeight(root, 0);

    // printing the level order of tree
    while (!q.empty()) {
        auto top = q.front(); q.pop();
        Node* node = top.first;
        int lvl = top.second;

        if (lvl > lastLevel) {
            cout << "
";
            lastLevel = lvl;
        }

        // all levels are printed
        if (lvl > height) break;


        if (node->data != -1) cout << node->data << " ";

        // printing null node
        else cout << "N ";

        // null node has no children
        if (node->data == -1) continue;

        if (node->left == nullptr) q.push({new Node(-1), lvl + 1});
        else q.push({node->left, lvl + 1});

        if (node->right == nullptr) q.push({new Node(-1), lvl + 1});
        else q.push({node->right, lvl + 1});
    }
}
//Driver Code Ends

// Inorder traversal: store node values in a vector
void inorder(Node* root, vector<int>& values) {
    if (!root) return;
    inorder(root->left, values);
    values.push_back(root->data);
    inorder(root->right, values);
}

// Build right-skewed tree from vector
Node* buildRightSkewedTree(const vector<int>& values) {
    Node* dummy = new Node(-1);
    Node* prev = dummy;

    for (int val : values) {
        prev->right = new Node(val);
        prev->left = nullptr;
        prev = prev->right;
    }

    Node* newRoot = dummy->right;
    delete dummy;
    return newRoot;
}

// Flatten BST 
Node* flattenBST(Node* root) {
    vector<int> values;
    inorder(root, values);  

    // Rebuild as right-skewed tree
    return buildRightSkewedTree(values); 
}


//Driver Code Starts

int main() {

    // Build BST
    //       5 
    //     /   \ 
    //    3     7 
    //   / \   / \ 
    //  2   4 6   8
    Node* root = new Node(5);
    root->left = new Node(3);
    root->right = new Node(7);
    root->left->left = new Node(2);
    root->left->right = new Node(4);
    root->right->left = new Node(6);
    root->right->right = new Node(8);

    Node* flatRoot = flattenBST(root);
    levelOrder(flatRoot); 

    return 0;
}

//Driver Code Ends
Java
//Driver Code Starts
import java.util.LinkedList;
import java.util.Queue;
import java.util.List;
import java.util.ArrayList;

// Node structure
class Node {
    int data;
    Node left, right;
    Node(int data) {
        this.data = data;
        left = right = null;
    }
}

public class GFG {

   // Calculate Height
     static int getHeight( Node root, int h ) {
        if( root == null ) return h-1;
        
        return Math.max(getHeight(root.left, h+1), getHeight(root.right, h+1));
    }
    
    // Print Level Order
    static void levelOrder(Node root) {
        Queue<List<Object>> queue = new LinkedList<>();
        queue.offer(List.of(root, 0));
        
        int lastLevel = 0;
        
        // function to get the height of tree
        int height = getHeight(root, 0);
        
        // printing the level order of tree
        while( !queue.isEmpty()) {
            List<Object> top = queue.poll();
            
            Node node = (Node) top.get(0);
            int lvl = (int) top.get(1);
            
            if( lvl > lastLevel ) {
                System.out.println();
                lastLevel = lvl;
            }
            
            // all levels are printed
            if( lvl > height ) break;
            
            // printing null node
            System.out.print((node.data == -1 ? "N" : node.data) + " ");
            
            // null node has no children
            if( node.data == -1 ) continue;
            
            if( node.left == null ) queue.offer(List.of(new Node(-1), lvl+1));
            else queue.offer(List.of(node.left, lvl+1));
            
            if( node.right == null ) queue.offer(List.of(new Node(-1), lvl+1));
            else queue.offer(List.of(node.right, lvl+1));
        }
    }
//Driver Code Ends

    // Inorder traversal: store node values in a list
    static void inorder(Node root, List<Integer> values) {
        if (root == null) return;
        inorder(root.left, values);
        values.add(root.data);
        inorder(root.right, values);
    }

    // Build right-skewed tree from list
    static Node buildRightSkewedTree(List<Integer> values) {
        Node dummy = new Node(-1);
        Node prev = dummy;

        for (int val : values) {
            prev.right = new Node(val);
            prev.left = null;
            prev = prev.right;
        }

        return dummy.right;
    }

    // Flatten BST 
    static Node flattenBST(Node root) {
        List<Integer> values = new ArrayList<>();
        inorder(root, values); 
        
        // Rebuild as right-skewed tree
        return buildRightSkewedTree(values); 
    }


//Driver Code Starts
    public static void main(String[] args) {
        
         // Build BST
    //       5 
    //     /   \ 
    //    3     7 
    //   / \   / \ 
    //  2   4 6   8
    
        Node root = new Node(5);
        root.left = new Node(3);
        root.right = new Node(7);
        root.left.left = new Node(2);
        root.left.right = new Node(4);
        root.right.left = new Node(6);
        root.right.right = new Node(8);

        Node flatRoot = flattenBST(root);
        levelOrder(flatRoot); 
    }
}

//Driver Code Ends
Python
#Driver Code Starts
from collections import deque

# Node structure
class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
# Calculate Height
def getHeight(root, h):
    if root is None:
        return h - 1
    return max(getHeight(root.left, h + 1), getHeight(root.right, h + 1))

# Print level order traversal
def levelOrder(root):
    queue = deque([[root, 0]])
    lastLevel = 0

    # function to get the height of tree
    height = getHeight(root, 0)

    # printing the level order of tree
    while queue:
        node, lvl = queue.popleft()

        if lvl > lastLevel:
            print()
            lastLevel = lvl

        # all levels are printed
        if lvl > height:
            break

        # printing null node
        print("N" if node.data == -1 else node.data, end=" ")

        # null node has no children
        if node.data == -1:
            continue

        if node.left is None:
            queue.append([Node(-1), lvl + 1])
        else:
            queue.append([node.left, lvl + 1])

        if node.right is None:
            queue.append([Node(-1), lvl + 1])
        else:
            queue.append([node.right, lvl + 1])

#Driver Code Ends

# Inorder traversal: store node values in a list
def inorder(root, values):
    if not root:
        return
    inorder(root.left, values)
    values.append(root.data)
    inorder(root.right, values)

# Build right-skewed tree from list
def buildRightSkewedTree(values):
    dummy = Node(-1)
    prev = dummy
    for val in values:
        prev.right = Node(val)
        prev.left = None
        prev = prev.right
    return dummy.right

# Flatten BST (naive approach)
def flattenBST(root):
    values = []
    inorder(root, values)    
    
    # Rebuild as right-skewed tree
    return buildRightSkewedTree(values) 


#Driver Code Starts
if __name__ == "__main__":
    
    #   Build BST
    #       5 
    #     /   \ 
    #    3     7 
    #   / \   / \ 
    #   2   4 6   8
    root = Node(5)
    root.left = Node(3)
    root.right = Node(7)
    root.left.left = Node(2)
    root.left.right = Node(4)
    root.right.left = Node(6)
    root.right.right = Node(8)
    
    flatRoot = flattenBST(root)
    levelOrder(flatRoot) 

#Driver Code Ends
C#
//Driver Code Starts
using System;
using System.Collections.Generic;

// Node structure
class Node {
    public int data;
    public Node left, right;
    public Node(int data) {
        this.data = data;
        left = right = null;
    }
}

class GFG {

// Calculate Height
      static int getHeight(Node root, int h) {
        if (root == null) return h - 1;
        return Math.Max(getHeight(root.left, h + 1), getHeight(root.right, h + 1));
    }

// Print level order
    static void levelOrder(Node root) {
        Queue<(Node, int)> queue = new Queue<(Node, int)>();
        queue.Enqueue((root, 0));

        int lastLevel = 0;

        // function to get the height of tree
        int height = getHeight(root, 0);

        // printing the level order of tree
        while (queue.Count > 0) {
            var (node, lvl) = queue.Dequeue();

            if (lvl > lastLevel) {
                Console.WriteLine();
                lastLevel = lvl;
            }

            // all levels are printed
            if (lvl > height) break;

            // printing null node
            Console.Write((node.data == -1 ? "N" : node.data.ToString()) + " ");

            // null node has no children
            if (node.data == -1) continue;

            if (node.left == null) queue.Enqueue((new Node(-1), lvl + 1));
            else queue.Enqueue((node.left, lvl + 1));

            if (node.right == null) queue.Enqueue((new Node(-1), lvl + 1));
            else queue.Enqueue((node.right, lvl + 1));
        }
    }


//Driver Code Ends

    // Inorder traversal: store node values in a list
    static void inorder(Node root, List<int> values) {
        if (root == null) return;
        inorder(root.left, values);
        values.Add(root.data);
        inorder(root.right, values);
    }

    // Build right-skewed tree from list
    static Node buildRightSkewedTree(List<int> values) {
        Node dummy = new Node(-1);
        Node prev = dummy;
        foreach (int val in values) {
            prev.right = new Node(val);
            prev.left = null;
            prev = prev.right;
        }
        return dummy.right;
    }

    // Flatten BST 
    static Node flattenBST(Node root) {
        List<int> values = new List<int>();
        inorder(root, values);     
        
        // Rebuild as right-skewed tree
        return buildRightSkewedTree(values); 
    }

//Driver Code Starts
    static void Main(string[] args) {
        
    // Build BST
    //       5 
    //     /   \ 
    //    3     7 
    //   / \   / \ 
    //  2   4 6   8
        Node root = new Node(5);
        root.left = new Node(3);
        root.right = new Node(7);
        root.left.left = new Node(2);
        root.left.right = new Node(4);
        root.right.left = new Node(6);
        root.right.right = new Node(8);

        Node flatRoot = flattenBST(root);
        levelOrder(flatRoot);  
    }
}

//Driver Code Ends
JavaScript
//Driver Code Starts
// Node structure
class Node {
    constructor(data) {
        this.data = data;
        this.left = null;
        this.right = null;
    }
}

class QNode {
    constructor(data) {
        this.data = data;
        this.next = null;
    }
}

class Queue {
    constructor() {
        this.front = null;
        this.rear = null;
    }

    isEmpty() {
        return this.front === null;
    }

    enqueue(x) {
        let newNode = new QNode(x);
        if (this.rear === null) {
            this.front = this.rear = newNode;
            return;
        }
        this.rear.next = newNode;
        this.rear = newNode;
    }

    dequeue() {
        if (this.front === null)
            return null;

        let temp = this.front;
        this.front = this.front.next;

        if (this.front === null)
            this.rear = null;

        return temp.data;
    }
}

// Calculate height
function getHeight(root, h) {
    if (root === null) return h - 1;
    return Math.max(getHeight(root.left, h + 1), getHeight(root.right, h + 1));
}

function levelOrder(root) {
    let queue = [];
    queue.push([root, 0]);

    let lastLevel = 0;

    // get the height of tree
    let height = getHeight(root, 0);

    // printing the level order of tree
    while (queue.length > 0) {
        let [node, lvl] = queue.shift();

        if (lvl > lastLevel) {
            console.log("");
            lastLevel = lvl;
        }

        // all levels are printed
        if (lvl > height) break;

        // printing null node
        process.stdout.write((node.data === -1 ? "N" : node.data) + " ");

        // null node has no children
        if (node.data === -1) continue;

        if (node.left === null) queue.push([new Node(-1), lvl + 1]);
        else queue.push([node.left, lvl + 1]);

        if (node.right === null) queue.push([new Node(-1), lvl + 1]);
        else queue.push([node.right, lvl + 1]);
    }
}

//Driver Code Ends

// Inorder traversal: store node values in a list
function inorder(root, values) {
    if (!root) return;
    inorder(root.left, values);
    values.push(root.data);
    inorder(root.right, values);
}

// Build right-skewed tree from list
function buildRightSkewedTree(values) {
    const dummy = new Node(-1);
    let prev = dummy;
    for (let val of values) {
        prev.right = new Node(val);
        prev.left = null;
        prev = prev.right;
    }
    return dummy.right;
}

// Flatten BST 
function flattenBST(root) {
    const values = [];
    inorder(root, values); 
    
    // Rebuild as right-skewed tree
    return buildRightSkewedTree(values); 
}

//Driver Code Starts


// Driver code

     // Build BST
    //       5 
    //     /   \ 
    //    3     7 
    //   / \   / \ 
    //  2   4 6   8
let root = new Node(5);
root.left = new Node(3);
root.right = new Node(7);
root.left.left = new Node(2);
root.left.right = new Node(4);
root.right.left = new Node(6);
root.right.right = new Node(8);

const flatRoot = flattenBST(root);
levelOrder(flatRoot); 

//Driver Code Ends

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).
C++
//Driver Code Starts
#include <iostream>
#include <queue>
using namespace std;

// Node structure
struct Node {
    int data;
    Node* left;
    Node* right;
    Node(int data)
    {
        this->data = data;
        left = NULL;
        right = NULL;
    }
};

// Calculate Height
int getHeight(Node* root, int h) {
    if (root == nullptr) return h - 1;
    return max(getHeight(root->left, h + 1), getHeight(root->right, h + 1));
}

// Print Level Order
void levelOrder(Node* root) {
    queue<pair<Node*, int>> q;
    q.push({root, 0});

    int lastLevel = 0;

    // function to get the height of tree
    int height = getHeight(root, 0);

    // printing the level order of tree
    while (!q.empty()) {
        auto top = q.front(); q.pop();
        Node* node = top.first;
        int lvl = top.second;

        if (lvl > lastLevel) {
            cout << "
";
            lastLevel = lvl;
        }

        // all levels are printed
        if (lvl > height) break;


        if (node->data != -1) cout << node->data << " ";

        // printing null node
        else cout << "N ";

        // null node has no children
        if (node->data == -1) continue;

        if (node->left == nullptr) q.push({new Node(-1), lvl + 1});
        else q.push({node->left, lvl + 1});

        if (node->right == nullptr) q.push({new Node(-1), lvl + 1});
        else q.push({node->right, lvl + 1});
    }
}

//Driver Code Ends

// Function to perform in-order traversal
// recursively
void inorder(Node* curr, Node*& prev)
{
    // Base case
    if (curr == NULL)
        return;
    inorder(curr->left, prev);
    prev->left = NULL;
    prev->right = curr;
    prev = curr;
    inorder(curr->right, prev);
}

// Function to flatten binary tree
Node* flattenBST(Node* root)
{
    // Dummy node
    Node* dummy = new Node(-1);

    // Pointer to previous element
    Node* prev = dummy;
    inorder(root, prev);

    prev->left = NULL;
    prev->right = NULL;
    Node* newRoot = dummy->right;
    delete dummy;
    return newRoot;
}


//Driver Code Starts
int main()
{
     // Build BST
    //       5 
    //     /   \ 
    //    3     7 
    //   / \   / \ 
    //  2   4 6   8
    Node* root = new Node(5);
    root->left = new Node(3);
    root->right = new Node(7);
    root->left->left = new Node(2);
    root->left->right = new Node(4);
    root->right->left = new Node(6);
    root->right->right = new Node(8);
    levelOrder(flattenBST(root));

    return 0;
}

//Driver Code Ends
Java
//Driver Code Starts
import java.util.LinkedList;
import java.util.Queue;
import java.util.List;
import java.util.ArrayList;

class GFG{

// Node structure
static class Node
{
  int data;
  Node left;
  Node right;
   
  Node(int data)
  {
    this.data = data;
    left = null;
    right = null;
  }
};

// Calculate Height
    static int getHeight( Node root, int h ) {
        if( root == null ) return h-1;
        
        return Math.max(getHeight(root.left, h+1), getHeight(root.right, h+1));
    }

// Print level Order
    static void levelOrder(Node root) {
        Queue<List<Object>> queue = new LinkedList<>();
        queue.offer(List.of(root, 0));
        
        int lastLevel = 0;
        
        // function to get the height of tree
        int height = getHeight(root, 0);
        
        // printing the level order of tree
        while( !queue.isEmpty()) {
            List<Object> top = queue.poll();
            
            Node node = (Node) top.get(0);
            int lvl = (int) top.get(1);
            
            if( lvl > lastLevel ) {
                System.out.println();
                lastLevel = lvl;
            }
            
            // all levels are printed
            if( lvl > height ) break;
            
            // printing null node
            System.out.print((node.data == -1 ? "N" : node.data) + " ");
            
            // null node has no children
            if( node.data == -1 ) continue;
            
            if( node.left == null ) queue.offer(List.of(new Node(-1), lvl+1));
            else queue.offer(List.of(node.left, lvl+1));
            
            if( node.right == null ) queue.offer(List.of(new Node(-1), lvl+1));
            else queue.offer(List.of(node.right, lvl+1));
        }
    }
//Driver Code Ends


static  Node prev;
   
// Function to perform 
// in-order traversal
static void Inorder(Node curr)
{
  // Base case
  if (curr == null)
    return;
  Inorder(curr.left);
  prev.left = null;
  prev.right = curr;
  prev = curr;
  Inorder(curr.right);
}
 
// Function to flatten binary tree 
static Node flattenBST(Node root)
{
  // Dummy node
  Node dummy = new Node(-1);
 
  // Pointer to previous
  // element
  prev = dummy;
  Inorder(root);
 
  prev.left = null;
  prev.right = null;
  Node newRoot = dummy.right;
  return newRoot;
}

//Driver Code Starts
 
public static void main(String[] args)
{
    
     // Build BST
    //       5 
    //     /   \ 
    //    3     7 
    //   / \   / \ 
    //  2   4 6   8
  Node root = new Node(5);
  root.left = new Node(3);
  root.right = new Node(7);
  root.left.left = new Node(2);
  root.left.right = new Node(4);
  root.right.left = new Node(6);
  root.right.right = new Node(8);
  levelOrder(flattenBST(root));
}
}

//Driver Code Ends
Python
#Driver Code Starts
from collections import deque

# Node structure
class Node :
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None


# Calculate Height
def getHeight(root, h):
    if root is None:
        return h - 1
    return max(getHeight(root.left, h + 1), getHeight(root.right, h + 1))


# Print Level Order
def levelOrder(root):
    queue = deque([[root, 0]])
    lastLevel = 0

    # function to get the height of tree
    height = getHeight(root, 0)

    # printing the level order of tree
    while queue:
        node, lvl = queue.popleft()

        if lvl > lastLevel:
            print()
            lastLevel = lvl

        # all levels are printed
        if lvl > height:
            break

        # printing null node
        print("N" if node.data == -1 else node.data, end=" ")

        # null node has no children
        if node.data == -1:
            continue

        if node.left is None:
            queue.append([Node(-1), lvl + 1])
        else:
            queue.append([node.left, lvl + 1])

        if node.right is None:
            queue.append([Node(-1), lvl + 1])
        else:
            queue.append([node.right, lvl + 1])
#Driver Code Ends


global prev

# Function to perform in-order traversal
# recursively
def inorder(curr):
    global prev
    # Base case
    if (curr == None):
        return
    inorder(curr.left)
    prev.left = None
    prev.right = curr
    prev = curr
    inorder(curr.right)


# Function to flatten binary tree
def flattenBST(root):
    global prev
    # Dummy node
    dummy = Node(-1)

    # Pointer to previous element
    prev = dummy
    inorder(root)

    prev.left = None
    prev.right = None
    newRoot = dummy.right

    return newRoot


#Driver Code Starts
if __name__ == '__main__':
    
     #   Build BST
    #       5 
    #     /   \ 
    #    3     7 
    #   / \   / \ 
    #   2   4 6   8
    root = Node(5)
    root.left = Node(3)
    root.right = Node(7)
    root.left.left = Node(2)
    root.left.right = Node(4)
    root.right.left = Node(6)
    root.right.right = Node(8)
    levelOrder(flattenBST(root))
#Driver Code Ends
C#
//Driver Code Starts
using System;
using System.Collections.Generic;

public class GFG {

    // Node structure
    public class Node {
        public int data;
        public Node left;
        public Node right;

        public Node(int data)
        {
            this.data = data;
            left = null;
            right = null;
        }
    };

// Calculate Height
    static int getHeight(Node root, int h) {
        if (root == null) return h - 1;
        return Math.Max(getHeight(root.left, h + 1),
                           getHeight(root.right, h + 1));
    }

// Print Level Order
    static void levelOrder(Node root) {
        Queue<(Node, int)> queue = new Queue<(Node, int)>();
        queue.Enqueue((root, 0));

        int lastLevel = 0;

        // function to get the height of tree
        int height = getHeight(root, 0);

        // printing the level order of tree
        while (queue.Count > 0) {
            var (node, lvl) = queue.Dequeue();

            if (lvl > lastLevel) {
                Console.WriteLine();
                lastLevel = lvl;
            }

            // all levels are printed
            if (lvl > height) break;

            // printing null node
            Console.Write((node?.data == -1 ? "N" : node?.data.ToString()) + " ");

            // null node has no children
            if (node?.data == -1) continue;

            if (node.left == null) queue.Enqueue((new Node(-1), lvl + 1));
            else queue.Enqueue((node.left, lvl + 1));

            if (node.right == null) queue.Enqueue((new Node(-1), lvl + 1));
            else queue.Enqueue((node.right, lvl + 1));
        }
    }
    
//Driver Code Ends

    static Node prev;

    // Function to perform
    // in-order traversal
    static void Inorder(Node curr)
    {
        // Base case
        if (curr == null)
            return;
        Inorder(curr.left);
        prev.left = null;
        prev.right = curr;
        prev = curr;
        Inorder(curr.right);
    }

    // Function to flatten binary tree
    static Node flattenBST(Node parent)
    {
        // Dummy node
        Node dummy = new Node(-1);

        // Pointer to previous
        // element
        prev = dummy;
        Inorder(parent);

        prev.left = null;
        prev.right = null;
        Node newRoot = dummy.right;
        return newRoot;
    }


//Driver Code Starts
    public static void Main(string[] args)
    {
         // Build BST
    //       5 
    //     /   \ 
    //    3     7 
    //   / \   / \ 
    //  2   4 6   8
        Node root = new Node(5);
        root.left = new Node(3);
        root.right = new Node(7);
        root.left.left = new Node(2);
        root.left.right = new Node(4);
        root.right.left = new Node(6);
        root.right.right = new Node(8);
        levelOrder(flattenBST(root));
    }
}
//Driver Code Ends
JavaScript
//Driver Code Starts
// Node structure
class Node {
    constructor(data) {
        this.data = data;
        this.left = null;
        this.right = null;
    }
}

class QNode {
    constructor(data) {
        this.data = data;
        this.next = null;
    }
}

class Queue {
    constructor() {
        this.front = null;
        this.rear = null;
    }

    isEmpty() {
        return this.front === null;
    }

    enqueue(x) {
        let newNode = new QNode(x);
        if (this.rear === null) {
            this.front = this.rear = newNode;
            return;
        }
        this.rear.next = newNode;
        this.rear = newNode;
    }

    dequeue() {
        if (this.front === null)
            return null;

        let temp = this.front;
        this.front = this.front.next;

        if (this.front === null)
            this.rear = null;

        return temp.data;
    }
}

// Calculate Height
function getHeight(root, h) {
    if (root === null) return h - 1;
    return Math.max(getHeight(root.left, h + 1), getHeight(root.right, h + 1));
}

// Print level Order
function levelOrder(root) {
    let queue = [];
    queue.push([root, 0]);

    let lastLevel = 0;

    // get the height of tree
    let height = getHeight(root, 0);

    // printing the level order of tree
    while (queue.length > 0) {
        let [node, lvl] = queue.shift();

        if (lvl > lastLevel) {
            console.log("");
            lastLevel = lvl;
        }

        // all levels are printed
        if (lvl > height) break;

        // printing null node
        process.stdout.write((node.data === -1 ? "N" : node.data) + " ");

        // null node has no children
        if (node.data === -1) continue;

        if (node.left === null) queue.push([new Node(-1), lvl + 1]);
        else queue.push([node.left, lvl + 1]);

        if (node.right === null) queue.push([new Node(-1), lvl + 1]);
        else queue.push([node.right, lvl + 1]);
    }
}

//Driver Code Ends

// Function to perform in-order traversal recursively
function inorder(curr, prev) {
    // Base case
    if (curr === null) return;

    inorder(curr.left, prev);
    prev.node.right = curr;
    curr.left = null;
    prev.node = curr;

    inorder(curr.right, prev);
}

// Function to flatten binary tree
function flattenBST(root) {
    // Dummy node
    const dummy = new Node(-1);

    // Pointer to previous element
    const prev = { node: dummy };

    inorder(root, prev);

    prev.node.left = null;
    prev.node.right = null;
    const newRoot = dummy.right;
    return newRoot;
}

//Driver Code Starts

// Driver code
 // Build BST
    //       5 
    //     /   \ 
    //    3     7 
    //   / \   / \ 
    //  2   4 6   8
let root = new Node(5);
root.left = new Node(3);
root.right = new Node(7);
root.left.left = new Node(2);
root.left.right = new Node(4);
root.right.left = new Node(6);
root.right.right = new Node(8);

const flatRoot = flattenBST(root);
levelOrder(flatRoot);
//Driver Code Ends

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