Flatten BST to sorted list | Increasing order
Given a binary search tree, the task is to flatten it to a sorted list. Precisely, the value of each node must be lesser 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: 2 3 4 5 6 7 8
Input: 1 \ 2 \ 3 \ 4 \ 5 Output: 1 2 3 4 5
Approach: A simple approach will be to recreate the BST from its in-order traversal. This will take O(N) extra space where N is the number of nodes in BST.
C++
// C++ implementation of the approach #include <bits/stdc++.h> using namespace std; // Node of the binary tree struct node { int data; node* left; node* right; node( int data) { this ->data = data; left = NULL; right = NULL; } }; // Function to print flattened // binary Tree void print(node* parent) { node* curr = parent; while (curr != NULL) cout << curr->data << " " , curr = curr->right; } // Function to perform in-order traversal // recursively void inorder(vector< int >& traversal, node* parent) { // Base Case if (parent == NULL) return ; inorder(traversal, parent->left); // Storing the values in the vector traversal.push_back(parent->data); inorder(traversal, parent->right); } void form( int pos, vector< int > traversal, node*& prev) { // Base Case if (pos == traversal.size()) return ; prev->right = new node(traversal[pos]); prev->left = NULL; prev = prev->right; // calling for the next element of the vector form(pos + 1, traversal, prev); } // Function to flatten binary tree using // level order traversal node* flatten(node* parent) { // Dummy node node* dummy = new node(-1); // Pointer to previous element node* prev = dummy; // vector to store the inorder traversal of the binary // tree vector< int > traversal; inorder(traversal, parent); // forming the sorted list from the vector obtained form(0, traversal, prev); prev->left = NULL; prev->right = NULL; node* ret = dummy->right; // Delete dummy node delete dummy; return ret; } int 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
import java.util.*; // Node of the binary tree class Node { int data; Node left; Node right; public Node( int data) { this .data = data; left = null ; right = null ; } } public class Main { // Function to print flattened binary tree static void print(Node parent) { Node curr = parent; while (curr != null ) { System.out.print(curr.data + " " ); curr = curr.right; } } // Function to perform in-order traversal recursively static void inorder(List<Integer> traversal, Node parent) { // Base Case if (parent == null ) return ; inorder(traversal, parent.left); // Storing the values in the list traversal.add(parent.data); inorder(traversal, parent.right); } static void form( int pos, List<Integer> traversal, Node[] prev) { // Base Case if (pos == traversal.size()) return ; prev[ 0 ].right = new Node(traversal.get(pos)); prev[ 0 ].left = null ; prev[ 0 ] = prev[ 0 ].right; // Calling for the next element of the list form(pos + 1 , traversal, prev); } // Function to flatten binary tree using level order // traversal static Node flatten(Node parent) { // Dummy node Node dummy = new Node(- 1 ); // Pointer to previous element Node[] prev = { dummy }; // List to store the inorder traversal of the binary // tree List<Integer> traversal = new ArrayList<>(); inorder(traversal, parent); // forming the sorted list from the list obtained form( 0 , traversal, prev); prev[ 0 ].left = null ; prev[ 0 ].right = null ; Node ret = dummy.right; // Delete dummy node dummy = null ; return ret; } public 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)); } } |
Python3
# Python code for the above approach # Node of the binary tree class Node: def __init__( self , data): self .data = data self .left = None self .right = None # Function to print flattened binary tree def print_flattened_tree(parent): curr = parent while curr is not None : print (curr.data, end = " " ) curr = curr.right # Function to perform in-order traversal recursively def inorder_traversal(traversal, parent): # Base Case if parent is None : return inorder_traversal(traversal, parent.left) # Storing the values in the list traversal.append(parent.data) inorder_traversal(traversal, parent.right) def form(pos, traversal, prev): # Base Case if pos = = len (traversal): return prev[ 0 ].right = Node(traversal[pos]) prev[ 0 ].left = None prev[ 0 ] = prev[ 0 ].right # Calling for the next element of the list form(pos + 1 , traversal, prev) # Function to flatten binary tree using level order traversal def flatten(parent): # Dummy node dummy = Node( - 1 ) # Pointer to previous element prev = [dummy] # List to store the inorder traversal of the binary tree traversal = [] inorder_traversal(traversal, parent) # forming the sorted list from the list obtained form( 0 , traversal, prev) prev[ 0 ].left = None prev[ 0 ].right = None ret = dummy.right # Delete dummy node dummy = None return ret if __name__ = = "__main__" : 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 function print_flattened_tree(flatten(root)) # This code is contributed by Prince Kumar |
C#
using System; using System.Collections.Generic; // Node of the binary tree public class Node { public int Data { get ; set ; } public Node Left { get ; set ; } public Node Right { get ; set ; } public Node( int data) { this .Data = data; this .Left = null ; this .Right = null ; } } class Program { // Function to print flattened binary tree static void Print(Node parent) { Node curr = parent; while (curr != null ) { Console.Write(curr.Data + " " ); curr = curr.Right; } } // Function to perform in-order traversal recursively static void Inorder(List< int > traversal, Node parent) { // Base Case if (parent == null ) return ; Inorder(traversal, parent.Left); // Storing the values in the list traversal.Add(parent.Data); Inorder(traversal, parent.Right); } static void Form( int pos, List< int > traversal, ref Node prev) { // Base Case if (pos == traversal.Count) return ; prev.Right = new Node(traversal[pos]); prev.Left = null ; prev = prev.Right; // calling for the next element of the list Form(pos + 1, traversal, ref prev); } // Function to flatten binary tree using level order // traversal static Node Flatten(Node parent) { // Dummy node Node dummy = new Node(-1); // Pointer to previous element Node prev = dummy; // list to store the inorder traversal of the binary // tree List< int > traversal = new List< int >(); Inorder(traversal, parent); // forming the sorted list from the list obtained Form(0, traversal, ref prev); prev.Left = null ; prev.Right = null ; Node ret = dummy.Right; // Return the resulting flattened tree return ret; } 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)); Console.ReadLine(); } } // This code is contributed by divyansh2212 |
Output
2 3 4 5 6 7 8
To improve upon that, we will simulate 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 in-order traversal and at each step.
- Set prev -> right = curr
- Set prev -> left = NULL
- Set prev = curr
This will improve the space complexity to O(H) in worst case as in-order traversal takes O(H) extra space.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach #include <bits/stdc++.h> using namespace std; // Node of the binary tree struct node { int data; node* left; node* right; node( int data) { this ->data = data; left = NULL; right = NULL; } }; // Function to print flattened // binary Tree void print(node* parent) { node* curr = parent; while (curr != NULL) cout << curr->data << " " , curr = curr->right; } // 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 using // level order traversal node* flatten(node* parent) { // Dummy node node* dummy = new node(-1); // Pointer to previous element node* prev = dummy; // Calling in-order traversal inorder(parent, prev); prev->left = NULL; prev->right = NULL; node* ret = dummy->right; // Delete dummy node delete dummy; return ret; } // Driver code int 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
// Java implementation of the // above approach import java.util.*; class GFG{ // Node of the binary tree static class node { int data; node left; node right; node( int data) { this .data = data; left = null ; right = null ; } }; // Function to print flattened // binary tree static void print(node parent) { node curr = parent; while (curr != null ) { System.out.print(curr.data + " " ); curr = curr.right; } } 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 using level order // traversal static node flatten(node parent) { // Dummy node node dummy = new node(- 1 ); // Pointer to previous // element prev = dummy; // Calling in-order // traversal Inorder(parent); prev.left = null ; prev.right = null ; node ret = dummy.right; // Delete dummy node //delete dummy; return ret; } // Driver code public 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 Debojyoti Mandal |
C#
// C# implementation of the // above approach using System; public class Program{ // Node of the binary tree public 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 tree static void print(node parent) { node curr = parent; while (curr != null ) { Console.Write(curr.data + " " ); curr = curr.right; } } 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 using level order // traversal static node flatten(node parent) { // Dummy node node dummy = new node(-1); // Pointer to previous // element prev = dummy; // Calling in-order // traversal Inorder(parent); prev.left = null ; prev.right = null ; node ret = dummy.right; // Delete dummy node //delete dummy; return ret; } // Driver code public 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 rrrtnx. |
Javascript
<script> // Javascript implementation of the approach // Node of the binary tree class node { constructor(data) { this .left = null ; this .right = null ; this .data = data; } } let prev; // Function to print flattened // binary Tree function print(parent) { let curr = parent; while (curr != null ) { document.write(curr.data + " " ); curr = curr.right; } } // Function to perform in-order traversal // recursively function inorder(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 using // level order traversal function flatten(parent) { // Dummy node let dummy = new node(-1); // Pointer to previous element prev = dummy; // Calling in-order traversal inorder(parent); prev.left = null ; prev.right = null ; let ret = dummy.right; // Delete dummy node return ret; } // Driver code 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); // Calling required function print(flatten(root)); // This code is contributed by divyeshrabadiya07 </script> |
Python3
# Python3 implementation of the approach global prev # Node of the binary tree class node : def __init__( self , data): self .data = data self .left = None self .right = None # Function to print flattened # binary Tree def printTree(parent): curr = parent while (curr ! = None ): print (curr.data,end = ' ' ) curr = curr.right # 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 using # level order traversal def flatten(parent): global prev # Dummy node dummy = node( - 1 ) # Pointer to previous element prev = dummy # Calling in-order traversal inorder(parent) prev.left = None prev.right = None ret = dummy.right # Delete dummy node return ret # Driver code if __name__ = = '__main__' : 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 function printTree(flatten(root)) |
Output:
2 3 4 5 6 7 8
Time Complexity: O(N)
Auxiliary Space: O(H)
Please Login to comment...