Open In App

Flatten Binary Tree in order of Zig Zag traversal

Last Updated : 17 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a Binary Tree, the task is to flatten it in order of ZigZag 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 2 5 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 ZigZag traversal of Binary Tree. 
Algorithm: 
 

  1. Create two stacks, “c_lev” and “n_lev” and to store the nodes of current and next level Binary tree.
  2. Create a variable “prev” and initialise it by parent node.
  3. Push right and left children of parent in the c_lev stack.
  4. Apply ZigZag traversal. Lets say “curr” is top most element in “c_lev”. Then, 
    • If ‘curr’ is NULL, continue.
    • Else push curr->left and curr->right on the stack “n_lev” in appropriate order. If we are performing left to right traversal then curr->left is pushed first else curr->right is pushed first.
    • Set prev = curr.

Below is the implementation of the above approach:
 

CPP




// 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
void flatten(node* parent)
{
    // Queue to store node
    // for BFS
    stack<node *> c_lev, n_lev;
 
    c_lev.push(parent->left);
    c_lev.push(parent->right);
 
    bool lev = 1;
    node* prev = parent;
 
    // Code for BFS
    while (c_lev.size()) {
 
        // Size of queue
        while (c_lev.size()) {
 
            // Front most node in
            // queue
            node* curr = c_lev.top();
            c_lev.pop();
 
            // Base case
            if (curr == NULL)
                continue;
            prev->right = curr;
            prev->left = NULL;
            prev = curr;
 
            // Pushing new elements
            // in queue
            if (!lev)
                n_lev.push(curr->left);
            n_lev.push(curr->right);
            if (lev)
                n_lev.push(curr->left);
        }
        lev = (!lev);
        c_lev = n_lev;
        while (n_lev.size())
            n_lev.pop();
    }
 
    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.io.*;
import java.util.*;
 
class GFG {
 
    static class node {
        int data;
        node left, right;
        node(int data)
        {
            this.data = data;
            left = right = null;
        }
    }
 
    // Function to flatten Binary tree
    static void flatten(node parent)
    {
        // Stack to store node for BFS
        Stack<node> c_lev = new Stack<>();
        Stack<node> n_lev = new Stack<>();
 
        c_lev.push(parent.left);
        c_lev.push(parent.right);
 
        boolean lev = true;
        node prev = parent;
 
        // Code for BFS
        while (c_lev.size() != 0) {
            // Size
            while (c_lev.size() != 0) {
                node curr = c_lev.peek();
                c_lev.pop();
 
                if (curr == null) {
                    continue;
                }
                prev.right = curr;
                prev.left = null;
                prev = curr;
 
                if (!lev) {
                    n_lev.push(curr.left);
                }
                n_lev.push(curr.right);
                if (lev) {
                    n_lev.push(curr.left);
                }
            }
            lev = (!lev);
            c_lev = (Stack)n_lev.clone();
            while (n_lev.size() != 0) {
                n_lev.pop();
            }
        }
        prev.left = null;
        prev.right = null;
    }
 
    static void print(node parent)
    {
        node curr = parent;
        while (curr != null) {
            System.out.print(curr.data + " ");
            curr = curr.right;
        }
    }
 
    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 lokeshmvs21.


Python3




# python implementation of the approach
# node of the binary tree
 
 
class node:
    # A utility function to create a new node
    def __init__(self, key):
        self.data = key
        self.left = None
        self.right = None
 
 
# Function to flatten Binary Tree
def flatten(parent):
    # queue to store for bfs
    c_lev = []
    n_lev = []
 
    c_lev.append(parent.left)
    c_lev.append(parent.right)
 
    lev = True
    prev = parent
 
    # code for bfs
    while(len(c_lev) > 0):
        # size of queue
        while(len(c_lev) > 0):
            # front most node in queue
            curr = c_lev.pop()
 
            # base case
            if(curr == None):
                continue
 
            prev.right = curr
            prev.left = None
            prev = curr
 
            # pushing new elements in queue
            if(lev == False):
                n_lev.append(curr.left)
            n_lev.append(curr.right)
            if(lev == True):
                n_lev.append(curr.left)
 
        if lev is True:
            lev = False
        else:
            lev = True
        c_lev = n_lev.copy()
        while(len(n_lev) > 0):
            n_lev.pop()
 
    prev.left = None
    prev.right = None
 
 
# function to print flattened binary tree
def printTree(parent):
    curr = parent
    while(curr is not 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 function
flatten(root)
 
printTree(root)
 
# This code is contributed by Yash Agarwal(yashagarwal2852002)


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
function flatten()
{
    // Queue to store node
    // for BFS
    var c_lev = [], n_lev = [];
 
    c_lev.push(parent.left);
    c_lev.push(parent.right);
 
    var lev = 1;
    var prev = parent;
 
    // Code for BFS
    while (c_lev.length!=0) {
 
        // Size of queue
        while (c_lev.length!=0) {
 
            // Front most node in
            // queue
            var curr = c_lev[c_lev.length-1];
            c_lev.pop();
 
            // Base case
            if (curr == null)
                continue;
 
            prev.right = curr;
            prev.left = null;
            prev = curr;
 
            // Pushing new elements
            // in queue
            if (!lev)
                n_lev.push(curr.left);
            n_lev.push(curr.right);
            if (lev)
                n_lev.push(curr.left);
        }
 
        lev = lev==0?1:0;
        c_lev = n_lev;
        n_lev = [];
    }
 
    prev.left = null;
    prev.right = null;
}
 
// Function to print flattened
// binary tree
function print()
{
    var curr = parent;
    while (curr != null)
    {
        document.write(curr.data + " ");
        curr = curr.right;
    }     
}
 
// Driver code
var parent = new node(1);
parent.left = new node(5);
parent.right = new node(2);
parent.left.left = new node(6);
parent.left.right = new node(4);
parent.right.left = new node(9);
parent.right.right = new node(3);
// Calling required functions
flatten();
print();
 
// This code is contributed by rrrtnx.
</script>


C#




using System;
using System.Collections.Generic;
 
public class Node {
    public int data;
    public Node left;
    public Node right;
 
    public Node(int data) {
        this.data = data;
        left = null;
        right = null;
    }
}
 
public class BinaryTree {
    public static void Flatten(Node parent) {
        Stack<Node> c_lev = new Stack<Node>();
        Stack<Node> n_lev = new Stack<Node>();
 
        c_lev.Push(parent.left);
        c_lev.Push(parent.right);
 
        bool lev = true;
        Node prev = parent;
 
        while (c_lev.Count > 0) {
            while (c_lev.Count > 0) {
                Node curr = c_lev.Pop();
                if (curr == null)
                    continue;
                prev.right = curr;
                prev.left = null;
                prev = curr;
                if (!lev)
                    n_lev.Push(curr.left);
                n_lev.Push(curr.right);
                if (lev)
                    n_lev.Push(curr.left);
            }
            lev = !lev;
            c_lev = n_lev;
            n_lev = new Stack<Node>();
        }
 
        prev.left = null;
        prev.right = null;
    }
 
    public static void Print(Node parent) {
        Node curr = parent;
        while (curr != null) {
            Console.Write(curr.data + " ");
            curr = curr.right;
        }
    }
 
    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);
 
        Flatten(root);
 
        Print(root);
    }
}


Output: 

1 2 5 6 4 9 3

 

Time Complexity: O(N) 
Space Complexity: O(N) where N is the size of Binary Tree.
 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads