Flatten Binary Tree in order of Level Order Traversal Last Updated : 17 Dec, 2021 Comments Improve Suggest changes Like Article Like Report Given a Binary Tree, the task is to flatten it in order of Level order traversal of the tree. In the flattened binary tree, the left node of all the nodes must be NULL.Examples: Input: 1 / \ 5 2 / \ / \ 6 4 9 3 Output: 1 5 2 6 4 9 3 Input: 1 \ 2 \ 3 \ 4 \ 5 Output: 1 2 3 4 5 Approach: We will solve this problem by simulating the Level order traversal of Binary Tree as follows: Create a queue to store the nodes of Binary tree.Create a variable "prev" and initialise it by parent node.Push left and right children of parent in the queue.Apply level order traversal. Lets say "curr" is front most element in queue. Then, If 'curr' is NULL, continue.Else push curr->left and curr->right in the queueSet prev = curr 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 flatten Binary tree using // level order traversal void flatten(node* parent) { // Queue to store nodes // for BFS queue<node*> q; q.push(parent->left); q.push(parent->right); node* prev = parent; // Code for BFS while (q.size()) { // Size of queue int s = q.size(); while (s--) { // Front most node in // the queue node* curr = q.front(); q.pop(); // Base case if (curr == NULL) continue; prev->right = curr; prev->left = NULL; prev = curr; // Pushing new elements // in queue q.push(curr->left); q.push(curr->right); } } prev->left = NULL; prev->right = NULL; } // Function to print flattened // Binary Tree void print(node* parent) { node* curr = parent; while (curr != NULL) cout << curr->data << " ", curr = curr->right; } // Driver code int main() { node* root = new node(1); root->left = new node(5); root->right = new node(2); root->left->left = new node(6); root->left->right = new node(4); root->right->left = new node(9); root->right->right = new node(3); // Calling required functions flatten(root); print(root); return 0; } Java // Java implementation of the 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 flatten Binary tree using // level order traversal static void flatten(node parent) { // Queue to store nodes // for BFS Queue<node> q = new LinkedList<>(); q.add(parent.left); q.add(parent.right); node prev = parent; // Code for BFS while (q.size() > 0) { // Size of queue int s = q.size(); while (s-- > 0) { // Front most node in // the queue node curr = q.peek(); q.remove(); // Base case if (curr == null) continue; prev.right = curr; prev.left = null; prev = curr; // Pushing new elements // in queue q.add(curr.left); q.add(curr.right); } } prev.left = null; prev.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; } } // Driver code public static void main(String[] args) { node root = new node(1); root.left = new node(5); root.right = new node(2); root.left.left = new node(6); root.left.right = new node(4); root.right.left = new node(9); root.right.right = new node(3); // Calling required functions flatten(root); print(root); } } // This code is contributed by Rajput-Ji Python3 # Python implementation of above algorithm # Utility class to create a node class node: def __init__(self, key): self.data = key self.left = self.right = None # Function to flatten Binary tree using # level order traversal def flatten( parent): # Queue to store nodes # for BFS q = [] q.append(parent.left) q.append(parent.right) prev = parent # Code for BFS while (len(q) > 0) : # Size of queue s = len(q) while (s > 0) : s = s - 1 # Front most node in # the queue curr = q[0] q.pop(0) # Base case if (curr == None): continue prev.right = curr prev.left = None prev = curr # appending elements # in queue q.append(curr.left) q.append(curr.right) prev.left = None prev.right = None # Function to print flattened # Binary Tree def print_(parent): curr = parent while (curr != None): print( curr.data , end=" ") curr = curr.right # Driver code root = node(1) root.left = node(5) root.right = node(2) root.left.left = node(6) root.left.right = node(4) root.right.left = node(9) root.right.right = node(3) # Calling required functions flatten(root) print_(root) # This code is contributed by Arnab Kundu C# // C# implementation of the approach using System; using System.Collections.Generic; class GFG { // 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 flatten Binary tree using // level order traversal static void flatten(node parent) { // Queue to store nodes // for BFS Queue<node> q = new Queue<node>(); q.Enqueue(parent.left); q.Enqueue(parent.right); node prev = parent; // Code for BFS while (q.Count > 0) { // Size of queue int s = q.Count; while (s-- > 0) { // Front most node in // the queue node curr = q.Peek(); q.Dequeue(); // Base case if (curr == null) continue; prev.right = curr; prev.left = null; prev = curr; // Pushing new elements // in queue q.Enqueue(curr.left); q.Enqueue(curr.right); } } prev.left = null; prev.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; } } // Driver code public static void Main(String[] args) { node root = new node(1); root.left = new node(5); root.right = new node(2); root.left.left = new node(6); root.left.right = new node(4); root.right.left = new node(9); root.right.right = new node(3); // Calling required functions flatten(root); print(root); } } // This code is contributed by Rajput-Ji JavaScript <script> // Javascript implementation of the approach // Node of the Binary tree class node { constructor(data) { this.data = data; this.left = null; this.right = null; } } // Function to flatten Binary tree using // level order traversal function flatten(parent) { // Queue to store nodes // for BFS let q = []; q.push(parent.left); q.push(parent.right); let prev = parent; // Code for BFS while (q.length > 0) { // Size of queue let s = q.length; while (s-- > 0) { // Front most node in // the queue let curr = q.shift(); // Base case if (curr == null) continue; prev.right = curr; prev.left = null; prev = curr; // Pushing new elements // in queue q.push(curr.left); q.push(curr.right); } } prev.left = null; prev.right = null; } // Function to print flattened // Binary Tree function print(parent) { let curr = parent; while (curr != null) { document.write(curr.data + " "); curr = curr.right; } } // Driver code let root = new node(1); root.left = new node(5); root.right = new node(2); root.left.left = new node(6); root.left.right = new node(4); root.right.left = new node(9); root.right.right = new node(3); // Calling required functions flatten(root); print(root); // This code is contributed by avanitrachhadiya2155 </script> Output : 1 5 2 6 4 9 3 Time Complexity: O(N) Space Complexity: O(N) where N is the size of Binary Tree. Comment More infoAdvertise with us Next Article Flatten Binary Tree in order of Level Order Traversal D DivyanshuShekhar1 Follow Improve Article Tags : Algorithms DSA Binary Tree tree-level-order Practice Tags : Algorithms Similar Reads DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on 7 min read Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s 12 min read Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge 14 min read Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir 8 min read Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta 15+ min read Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st 2 min read Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc 15 min read Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T 9 min read Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example 12 min read Selection Sort Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an 8 min read Like