Flatten binary tree in order of post-order traversal
Last Updated :
08 Aug, 2022
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 tree
struct node {
int data;
node* left;
node* right;
node(int data)
{
this->data = data;
left = NULL;
right = NULL;
}
};
// Function to print the flattened
// binary Tree
void print(node* parent)
{
node* curr = parent;
while (curr != NULL)
cout << curr->data << " ", curr = curr->right;
}
// Function to perform post-order traversal
// recursively
void 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 traversal
node* 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 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);
print(flatten(root));
return 0;
}
Java
// Java implementation of the approach
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;
}
};
static node prev;
// Function to print the 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 post-order traversal
// recursively
static 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 traversal
static 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 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);
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 Tree
def print_(parent):
curr = parent
while (curr != None):
print( curr.data ,end = " ")
curr = curr.right
prev = None
# Function to perform post-order traversal
# recursively
def 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 traversal
def 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 code
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)
print_(flatten(root))
# This code is contributed by Arnab Kundu
C#
// C# implementation of the approach
using System;
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;
}
};
static node prev;
// Function to print the flattened
// binary Tree
static void print(node parent)
{
node curr = parent;
while (curr != null)
{
Console.Write(curr.data + " ");
curr = curr.right;
}
}
// Function to perform post-order traversal
// recursively
static 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 traversal
static 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 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);
print(flatten(root));
}
}
// This code is contributed by Princi Singh
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;
}
};
var prev = null;
// Function to print the flattened
// binary Tree
function print(parent)
{
var curr = parent;
while (curr != null)
{
document.write(curr.data + " ");
curr = curr.right;
}
}
// Function to perform post-order traversal
// recursively
function 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 traversal
function 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 code
var 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>
Time complexity: O(N)
Auxiliary Space: O(N). since N extra space has been taken.
Similar Reads
Flatten Binary Tree in order of Level Order Traversal 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
7 min read
Find n-th node in Preorder traversal of a Binary Tree Given a binary tree. The task is to find the n-th node of preorder traversal.Examples: Input:Output: 50Explanation: Preorder Traversal is: 10 20 40 50 30 and value of 4th node is 50.Input:Output : 3Explanation: Preorder Traversal is: 7 2 3 8 5 and value of 3rd node is 3.Table of Content[Naive Approa
11 min read
Preorder Traversal of Binary Tree Preorder traversal is a tree traversal method that follows the Root-Left-Right order:The root node of the subtree is visited first.Next, the left subtree is recursively traversed.Finally, the right subtree is recursively traversed.How does Preorder Traversal work?Key Properties: Used in expression t
5 min read
Binary Search Tree (BST) Traversals â Inorder, Preorder, Post Order Given a Binary Search Tree, The task is to print the elements in inorder, preorder, and postorder traversal of the Binary Search Tree. Input: A Binary Search TreeOutput: Inorder Traversal: 10 20 30 100 150 200 300Preorder Traversal: 100 20 10 30 200 150 300Postorder Traversal: 10 30 20 150 300 200 1
10 min read
Inorder Traversal of Binary Tree Inorder traversal is a depth-first traversal method that follows this sequence:Left subtree is visited first.Root node is processed next.Right subtree is visited last.How does Inorder Traversal work?Key Properties:If applied to a Binary Search Tree (BST), it returns elements in sorted order.Ensures
5 min read
Create a binary tree from post order traversal and leaf node array Given 2 arrays, the first one containing postorder traversal sequence and the second one containing the information whether the corresponding node in the first array is a leaf node or a non-leaf node, create a binary tree and return its root and print it's inorder traversal. (There can be more than
6 min read