Flatten BST to sorted list | Decreasing order

10 Nov, 2021
Given a binary search tree, the task is to flatten it to a sorted list in decreasing order. Precisely, the value of each node must be greater than the values of all the nodes at its right, and its left node must be NULL after flattening. We must do it in O(H) extra space where ‘H’ is the height of BST.
Examples: 
Input: 
          5 
        /   \ 
       3     7 
      / \   / \ 
     2   4 6   8
Output: 8 7 6 5 4 3 2

Input:
      1
       \
        2
         \
          3
           \
            4
             \
              5
Output: 5 4 3 2 1
Approach: A simple approach will be to recreate the BST from its ‘reverse in-order’ traversal. This will take O(N) extra space where N is the number of nodes in BST. To improve upon that, we will simulate the reverse in-order traversal of a binary tree as follows:  
Create a dummy node.Create a variable called ‘prev’ and make it point to the dummy node.Perform reverse in-order traversal and at each step. Set prev -> right = currSet prev -> left = NULLSet prev = curr
Create a dummy node.
Create a variable called ‘prev’ and make it point to the dummy node.
Perform reverse in-order traversal and at each step. Set prev -> right = currSet prev -> left = NULLSet prev = curr
Set prev -> right = curr
Set prev -> left = NULL
Set prev = curr
This will improve the space complexity to O(H) in the worst case as in-order traversal takes O(H) extra space.
Below is the implementation of the above approach: 
C++
Java
Python3
C#
Javascript
// C++ implementation of the// above approach#include <bits/stdc++.h>using namespace std; // Node of the binary treestruct node {    int data;    node* left;    node* right;    node(int data)    {        this->data = data;        left = NULL;        right = NULL;    }}; // Function to print flattened// binary treevoid print(node* parent){    node* curr = parent;    while (curr != NULL)        cout << curr->data << " ", curr = curr->right;} // Function to perform reverse in-order traversalvoid revInorder(node* curr, node*& prev){    // Base case    if (curr == NULL)        return;    revInorder(curr->right, prev);    prev->left = NULL;    prev->right = curr;    prev = curr;    revInorder(curr->left, prev);} // Function to flatten binary tree using// level order traversalnode* flatten(node* parent){     // Dummy node    node* dummy = new node(-1);     // Pointer to previous element    node* prev = dummy;     // Calling in-order traversal    revInorder(parent, prev);     prev->left = NULL;    prev->right = NULL;    node* ret = dummy->right;     // Delete dummy node    delete dummy;    return ret;} // Driver codeint main(){    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);     // Calling required function    print(flatten(root));     return 0;}
// Java implementation of the// above approachimport java.util.*;class GFG{ // Node of the binary treestatic class node{  int data;  node left;  node right;     node(int data)  {    this.data = data;    left = null;    right = null;  }}; // Function to print flattened// binary treestatic void print(node parent){  node curr = parent;  while (curr != null)  {    System.out.print(curr.data + " ");    curr = curr.right;  }} static  node prev;   // Function to perform reverse// in-order traversalstatic void revInorder(node curr){  // Base case  if (curr == null)    return;  revInorder(curr.right);  prev.left = null;  prev.right = curr;  prev = curr;  revInorder(curr.left);} // Function to flatten binary// tree using level order// traversalstatic node flatten(node parent){  // Dummy node  node dummy = new node(-1);   // Pointer to previous  // element  prev = dummy;   // Calling in-order  // traversal  revInorder(parent);   prev.left = null;  prev.right = null;  node ret = dummy.right;   // Delete dummy node  //delete dummy;  return ret;} // Driver codepublic static void main(String[] args){  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);   // Calling required function  print(flatten(root));}} // This code is contributed by Amit Katiyar
# Python3 implementation of the# above approach # Node of the binary treeclass node:         def __init__(self, data):        self.data = data;        self.left = None;        self.right = None; # Function to print flattened# binary treedef printNode(parent):    curr = parent;    while (curr != None):        print(curr.data, end = ' ')        curr = curr.right;  # Function to perform reverse in-order traversaldef revInorder(curr):    global prev;    # Base case    if (curr == None):        return;    revInorder(curr.right);    prev.left = None;    prev.right = curr;    prev = curr;    revInorder(curr.left); # Function to flatten binary tree using# level order traversaldef flatten(parent):         global prev;    # Dummy node    dummy = node(-1);     # Pointer to previous element    prev = dummy;     # Calling in-order traversal    revInorder(parent);     prev.left = None;    prev.right = None;    ret = dummy.right;     return ret; # Driver codeprev = node(0)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); # Calling required functionprintNode(flatten(root)); # This code is contributed by rrrtnx.
// C# implementation of the// above approachusing System; class GFG{ // Node of the binary treepublic class node{  public int data;  public node left;  public node right;     public node(int data)  {    this.data = data;    left = null;    right = null;  }}; // Function to print flattened// binary treestatic void print(node parent){  node curr = parent;     while (curr != null)  {    Console.Write(curr.data + " ");    curr = curr.right;  }} static  node prev;   // Function to perform reverse// in-order traversalstatic void revInorder(node curr){     // Base case  if (curr == null)    return;     revInorder(curr.right);  prev.left = null;  prev.right = curr;  prev = curr;     revInorder(curr.left);} // Function to flatten binary// tree using level order// traversalstatic node flatten(node parent){     // Dummy node  node dummy = new node(-1);   // Pointer to previous  // element  prev = dummy;   // Calling in-order  // traversal  revInorder(parent);   prev.left = null;  prev.right = null;  node ret = dummy.right;     // Delete dummy node  //delete dummy;  return ret;} // Driver codepublic static void Main(String[] args){  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);   // Calling required function  print(flatten(root));}} // This code is contributed by Rajput-Ji
<script> // Javascript implementation of the approach // Node of the binary treeclass node{    constructor(data)    {        this.left = null;        this.right = null;        this.data = data;    }} // Function to print flattened// binary treefunction print(parent){    let curr = parent;    while (curr != null)    {        document.write(curr.data + " ");        curr = curr.right;    }} let prev; // Function to perform reverse// in-order traversalfunction revInorder(curr){         // Base case    if (curr == null)        return;             revInorder(curr.right);    prev.left = null;    prev.right = curr;    prev = curr;    revInorder(curr.left);} // Function to flatten binary// tree using level order// traversalfunction flatten(parent){         // Dummy node    let dummy = new node(-1);         // Pointer to previous    // element    prev = dummy;         // Calling in-order    // traversal    revInorder(parent);         prev.left = null;    prev.right = null;    let ret = dummy.right;         // Delete dummy node    //delete dummy;    return ret;} // Driver codelet 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); // Calling required functionprint(flatten(root)); // This code is contributed by divyeshrabadiya07 </script>
8 7 6 5 4 3 2
 
Time Complexity: O(N)Auxiliary Space: O(N)
amit143katiyar
Rajput-Ji
divyeshrabadiya07
pankajsharmagfg
rrrtnx
Algorithms
Binary Search Tree
Data Structures
Tree
Data Structures
Binary Search Tree
Tree
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is Hashing | A Complete Tutorial
Find if there is a path between two vertices in an undirected graph
How to Start Learning DSA?
Complete Roadmap To Learn DSA From Scratch
Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete
Binary Search Tree | Set 1 (Search and Insertion)
AVL Tree | Set 1 (Insertion)
Binary Search Tree | Set 2 (Delete)
A program to check if a binary tree is BST or not
Find postorder traversal of BST from preorder traversal