Flatten binary tree in order of post-order traversal

Given a binary tree, the task is to flatten it in order of its post-order traversal. In the flattened binary tree, the left node of all the nodes must be NULL.
Examples:Â
Input:
5
/ \
3 7
/ \ / \
2 4 6 8
Output: 2 4 3 6 8 7 5
Input:
1
\
2
\
3
\
4
\
5
Output: 5 4 3 2 1
A simple approach will be to recreate the Binary Tree from its post-order traversal. This will take O(N) extra space were N is the number of nodes in BST.
A better solution is to simulate post-order traversal of the given binary tree. Â
- Create a dummy node.
- Create variable called ‘prev’ and make it point to the dummy node.
- Perform post-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 the worst case as post-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 treestruct node {Â Â Â Â int data;Â Â Â Â node* left;Â Â Â Â node* right;Â Â Â Â node(int data)Â Â Â Â {Â Â Â Â Â Â Â Â this->data = data;Â Â Â Â Â Â Â Â left = NULL;Â Â Â Â Â Â Â Â right = NULL;Â Â Â Â }};Â
// Function to print the flattened// binary Treevoid print(node* parent){Â Â Â Â node* curr = parent;Â Â Â Â while (curr != NULL)Â Â Â Â Â Â Â Â cout << curr->data << " ", curr = curr->right;}Â
// Function to perform post-order traversal// recursivelyvoid postorder(node* curr, node*& prev){    // Base case    if (curr == NULL)        return;    postorder(curr->left, prev);    postorder(curr->right, prev);    prev->left = NULL;    prev->right = curr;    prev = curr;}Â
// Function to flatten the given binary tree// using post order traversalnode* flatten(node* parent){    // Dummy node    node* dummy = new node(-1);Â
    // Pointer to previous element    node* prev = dummy;Â
    // Calling post-order traversal    postorder(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);Â
    print(flatten(root));Â
    return 0;} |
Java
// Java implementation of the approachclass GFG{Â
// Node of the binary treestatic class node {Â Â Â Â int data;Â Â Â Â node left;Â Â Â Â node right;Â Â Â Â node(int data)Â Â Â Â {Â Â Â Â Â Â Â Â this.data = data;Â Â Â Â Â Â Â Â left = null;Â Â Â Â Â Â Â Â right = null;Â Â Â Â }};static node prev;Â
// Function to print the flattened// binary Treestatic void print(node parent){Â Â Â Â node curr = parent;Â Â Â Â while (curr != null)Â Â Â Â {Â Â Â Â Â Â Â Â System.out.print(curr.data + " ");Â Â Â Â Â Â Â Â curr = curr.right;Â Â Â Â }}Â
// Function to perform post-order traversal// recursivelystatic void postorder(node curr){    // Base case    if (curr == null)        return;    postorder(curr.left);    postorder(curr.right);    prev.left = null;    prev.right = curr;    prev = curr;}Â
// Function to flatten the given binary tree// using post order traversalstatic node flatten(node parent){    // Dummy node    node dummy = new node(-1);Â
    // Pointer to previous element    prev = dummy;Â
    // Calling post-order traversal    postorder(parent);Â
    prev.left = null;    prev.right = null;    node ret = dummy.right;Â
    // Delete dummy node    dummy = null;    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);Â
    print(flatten(root));}} Â
// This code is contributed by PrinciRaj1992 |
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 print the flattened# binary Treedef print_(parent):Â
    curr = parent    while (curr != None):        print( curr.data ,end = " ")        curr = curr.rightÂ
prev = NoneÂ
# Function to perform post-order traversal# recursivelydef postorder( curr ):         global prev         # Base case    if (curr == None):        return    postorder(curr.left)    postorder(curr.right)    prev.left = None    prev.right = curr    prev = currÂ
# Function to flatten the given binary tree# using post order traversaldef flatten(parent):Â
    global prev         # Dummy node    dummy = node(-1)Â
    # Pointer to previous element    prev = dummyÂ
    # Calling post-order traversal    postorder(parent)Â
    prev.left = None    prev.right = None    ret = dummy.rightÂ
    return retÂ
# Driver coderoot = 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)Â
print_(flatten(root))Â
Â
# This code is contributed by Arnab Kundu |
C#
// C# implementation of the 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;Â Â Â Â }};static node prev;Â
// Function to print the flattened// binary Treestatic void print(node parent){Â Â Â Â node curr = parent;Â Â Â Â while (curr != null)Â Â Â Â {Â Â Â Â Â Â Â Â Console.Write(curr.data + " ");Â Â Â Â Â Â Â Â curr = curr.right;Â Â Â Â }}Â
// Function to perform post-order traversal// recursivelystatic void postorder(node curr){    // Base case    if (curr == null)        return;    postorder(curr.left);    postorder(curr.right);    prev.left = null;    prev.right = curr;    prev = curr;}Â
// Function to flatten the given binary tree// using post order traversalstatic node flatten(node parent){    // Dummy node    node dummy = new node(-1);Â
    // Pointer to previous element    prev = dummy;Â
    // Calling post-order traversal    postorder(parent);Â
    prev.left = null;    prev.right = null;    node ret = dummy.right;Â
    // Delete dummy node    dummy = null;    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);Â
    print(flatten(root));}}Â
// This code is contributed by Princi Singh |
Javascript
<script>Â
// Javascript implementation of the approachÂ
// Node of the binary treeclass node {Â Â Â Â constructor(data)Â Â Â Â {Â Â Â Â Â Â Â Â this.data = data;Â Â Â Â Â Â Â Â this.left = null;Â Â Â Â Â Â Â Â this.right = null;Â Â Â Â }};Â
var prev = null;Â
// Function to print the flattened// binary Treefunction print(parent){Â Â Â Â var curr = parent;Â Â Â Â while (curr != null)Â Â Â Â {Â Â Â Â Â Â Â Â document.write(curr.data + " ");Â Â Â Â Â Â Â Â curr = curr.right;Â Â Â Â }}Â
// Function to perform post-order traversal// recursivelyfunction postorder(curr){         // Base case    if (curr == null)        return;             postorder(curr.left);    postorder(curr.right);    prev.left = null;    prev.right = curr;    prev = curr;}Â
// Function to flatten the given binary tree// using post order traversalfunction flatten(parent){         // Dummy node    var dummy = new node(-1);Â
    // Pointer to previous element    prev = dummy;Â
    // Calling post-order traversal    postorder(parent);Â
    prev.left = null;    prev.right = null;    var ret = dummy.right;Â
    // Delete dummy node    dummy = null;    return ret;}Â
// Driver codevar 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);Â
print(flatten(root));Â
// This code is contributed by noob2000Â
</script> |
Output:Â
2 4 3 6 8 7 5
Â
Time complexity: O(N)
Auxiliary Space: O(N). Â since N extra space has been taken.
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



