Print the nodes of binary tree as they become the leaf node
Last Updated :
28 Feb, 2024
Given a binary tree. First print all leaf nodes, after that remove all the leaf nodes from the tree and now print all the new formed leaf nodes and keep doing this until all the nodes are removed from the tree.
Examples :
Input :
8
/ \
3 10
/ \ / \
1 6 14 4
/ \
7 13
Output :
4 6 7 13 14
1 10
3
8
Source :Flipkart On Campus Recruitment
Approach : The idea is to perform simple dfs and assign different values to each node on the basis of following conditions:
- Initially assign all the nodes with value as 0.
- Now, Assign all the nodes with the value as (maximum value of both child)+1.
Tree before DFS: A temporary value zero is assigned to all of the nodes.

Tree after DFS: Nodes are assigned with the value as (maximum value of both child)+1.

Now, you can see in the above tree that after all the values are assigned to each node, the task now reduces to print the tree on the basis of increasing order of node values assigned to them.
Below is the implementation of above approach:
C++
// C++ program to print the nodes of binary
// tree as they become the leaf node
#include <bits/stdc++.h>
using namespace std;
// Binary tree node
struct Node {
int data;
int order;
struct Node* left;
struct Node* right;
};
// Utility function to allocate a new node
struct Node* newNode(int data, int order)
{
struct Node* node = new Node;
node->data = data;
node->order = order;
node->left = NULL;
node->right = NULL;
return (node);
}
// Function for postorder traversal of tree and
// assigning values to nodes
void Postorder(struct Node* node, vector<pair<int, int> >& v)
{
if (node == NULL)
return;
/* first recur on left child */
Postorder(node->left, v);
/* now recur on right child */
Postorder(node->right, v);
// If current node is leaf node, it's order will be 1
if (node->right == NULL && node->left == NULL) {
node->order = 1;
// make pair of assigned value and tree value
v.push_back(make_pair(node->order, node->data));
}
else {
// otherwise, the order will be:
// max(left_child_order, right_child_order) + 1
node->order = max((node->left)->order, (node->right)->order) + 1;
// make pair of assigned value and tree value
v.push_back(make_pair(node->order, node->data));
}
}
// Function to print leaf nodes in
// the given order
void printLeafNodes(int n, vector<pair<int, int> >& v)
{
// Sort the vector in increasing order of
// assigned node values
sort(v.begin(), v.end());
for (int i = 0; i < n; i++) {
if (v[i].first == v[i + 1].first)
cout << v[i].second << " ";
else
cout << v[i].second << "\n";
}
}
// Driver Code
int main()
{
struct Node* root = newNode(8, 0);
root->left = newNode(3, 0);
root->right = newNode(10, 0);
root->left->left = newNode(1, 0);
root->left->right = newNode(6, 0);
root->right->left = newNode(14, 0);
root->right->right = newNode(4, 0);
root->left->left->left = newNode(7, 0);
root->left->left->right = newNode(13, 0);
int n = 9;
vector<pair<int, int> > v;
Postorder(root, v);
printLeafNodes(n, v);
return 0;
}
Java
// Java program to print the nodes of binary
// tree as they become the leaf node
import java.util.*;
class GFG
{
// Binary tree node
static class Node
{
int data;
int order;
Node left;
Node right;
};
static class Pair
{
int first,second;
Pair(int a,int b)
{
first = a;
second = b;
}
}
// Utility function to allocate a new node
static Node newNode(int data, int order)
{
Node node = new Node();
node.data = data;
node.order = order;
node.left = null;
node.right = null;
return (node);
}
static Vector<Pair> v = new Vector<Pair>();
// Function for postorder traversal of tree and
// assigning values to nodes
static void Postorder(Node node)
{
if (node == null)
return;
/* first recur on left child */
Postorder(node.left);
/* now recur on right child */
Postorder(node.right);
// If current node is leaf node, it's order will be 1
if (node.right == null && node.left == null)
{
node.order = 1;
// make pair of assigned value and tree value
v.add(new Pair(node.order, node.data));
}
else
{
// otherwise, the order will be:
// max(left_child_order, right_child_order) + 1
node.order = Math.max((node.left).order, (node.right).order) + 1;
// make pair of assigned value and tree value
v.add(new Pair(node.order, node.data));
}
}
static class Sort implements Comparator<Pair>
{
// Used for sorting in ascending order of
// roll number
public int compare(Pair a, Pair b)
{
if(a.first != b.first)
return (a.first - b.first);
else
return (a.second-b.second);
}
}
// Function to print leaf nodes in
// the given order
static void printLeafNodes(int n)
{
// Sort the vector in increasing order of
// assigned node values
Collections.sort(v,new Sort());
for (int i = 0; i < v.size(); i++)
{
if (i != v.size()-1 && v.get(i).first == v.get(i + 1).first)
System.out.print( v.get(i).second + " ");
else
System.out.print( v.get(i).second + "\n");
}
}
// Driver Code
public static void main(String args[])
{
Node root = newNode(8, 0);
root.left = newNode(3, 0);
root.right = newNode(10, 0);
root.left.left = newNode(1, 0);
root.left.right = newNode(6, 0);
root.right.left = newNode(14, 0);
root.right.right = newNode(4, 0);
root.left.left.left = newNode(7, 0);
root.left.left.right = newNode(13, 0);
int n = 9;
Postorder(root);
printLeafNodes(n);
}
}
// This code is contributed by Arnab Kundu
C#
// C# program to print the nodes of binary
// tree as they become the leaf node
using System;
using System.Collections.Generic;
class GFG
{
// Binary tree node
public class Node
{
public int data;
public int order;
public Node left;
public Node right;
};
public class Pair
{
public int first,second;
public Pair(int a,int b)
{
first = a;
second = b;
}
}
// Utility function to allocate a new node
static Node newNode(int data, int order)
{
Node node = new Node();
node.data = data;
node.order = order;
node.left = null;
node.right = null;
return (node);
}
static List<Pair> v = new List<Pair>();
// Function for postorder traversal of
// tree and assigning values to nodes
static void Postorder(Node node)
{
if (node == null)
return;
/* first recur on left child */
Postorder(node.left);
/* now recur on right child */
Postorder(node.right);
// If current node is leaf node,
// it's order will be 1
if (node.right == null &&
node.left == null)
{
node.order = 1;
// make pair of assigned value
// and tree value
v.Add(new Pair(node.order, node.data));
}
else
{
// otherwise, the order will be:
// Max(left_child_order,
// right_child_order) + 1
node.order = Math.Max((node.left).order,
(node.right).order) + 1;
// make pair of assigned value
// and tree value
v.Add(new Pair(node.order, node.data));
}
}
// Used for sorting in ascending order
// of roll number
public static int compare(Pair a, Pair b)
{
if(a.first != b.first)
return (a.first - b.first);
else
return (a.second - b.second);
}
// Function to print leaf nodes in
// the given order
static void printLeafNodes(int n)
{
// Sort the List in increasing order
// of assigned node values
v.Sort(compare);
for (int i = 0; i < v.Count; i++)
{
if (i != v.Count - 1 &&
v[i].first == v[i + 1].first)
Console.Write(v[i].second + " ");
else
Console.Write(v[i].second + "\n");
}
}
// Driver Code
public static void Main(String[] args)
{
Node root = newNode(8, 0);
root.left = newNode(3, 0);
root.right = newNode(10, 0);
root.left.left = newNode(1, 0);
root.left.right = newNode(6, 0);
root.right.left = newNode(14, 0);
root.right.right = newNode(4, 0);
root.left.left.left = newNode(7, 0);
root.left.left.right = newNode(13, 0);
int n = 9;
Postorder(root);
printLeafNodes(n);
}
}
// This code is contributed
// by Arnab Kundu
JavaScript
<script>
// Javascript program to print the nodes of binary
// tree as they become the leaf node
class Node
{
constructor()
{
this.data = 0;
this.order = 0;
this.left = this.right = null;
}
}
class Pair
{
constructor(a, b)
{
this.first = a;
this.second = b;
}
}
// Utility function to allocate a new node
function newNode(data,order)
{
let node = new Node();
node.data = data;
node.order = order;
node.left = null;
node.right = null;
return (node);
}
let v = [];
// Function for postorder traversal of tree and
// assigning values to nodes
function Postorder(node)
{
if (node == null)
return;
/* first recur on left child */
Postorder(node.left);
/* now recur on right child */
Postorder(node.right);
// If current node is leaf node, it's order will be 1
if (node.right == null && node.left == null)
{
node.order = 1;
// make pair of assigned value and tree value
v.push(new Pair(node.order, node.data));
}
else
{
// otherwise, the order will be:
// max(left_child_order, right_child_order) + 1
node.order = Math.max((node.left).order, (node.right).order) + 1;
// make pair of assigned value and tree value
v.push(new Pair(node.order, node.data));
}
}
// Function to print leaf nodes in
// the given order
function printLeafNodes(n)
{
// Sort the vector in increasing order of
// assigned node values
v.sort(function(a,b){
if(a.first != b.first)
return (a.first - b.first);
else
return (a.second-b.second);})
for (let i = 0; i < v.length; i++)
{
if (i != v.length-1 && v[i].first == v[i+1].first)
document.write( v[i].second + " ");
else
document.write( v[i].second + "<br>");
}
}
// Driver Code
let root = newNode(8, 0);
root.left = newNode(3, 0);
root.right = newNode(10, 0);
root.left.left = newNode(1, 0);
root.left.right = newNode(6, 0);
root.right.left = newNode(14, 0);
root.right.right = newNode(4, 0);
root.left.left.left = newNode(7, 0);
root.left.left.right = newNode(13, 0);
let n = 9;
Postorder(root);
printLeafNodes(n);
// This code is contributed by avanitrachhadiya2155
</script>
Python3
# Python3 program to print the nodes of binary
# tree as they become the leaf node
# Binary tree node
class newNode:
def __init__(self, data,order):
self.data = data
self.order=order
self.left = None
self.right = None
# Function for postorder traversal of tree and
# assigning values to nodes
def Postorder(node,v):
if (node == None):
return
""" first recur on left child """
Postorder(node.left, v)
""" now recur on right child """
Postorder(node.right, v)
# If current node is leaf node,
# it's order will be 1
if (node.right == None and
node.left == None):
node.order = 1
# make pair of assigned value and tree value
v[0].append([node.order, node.data])
else:
# otherwise, the order will be:
# max(left_child_order, right_child_order) + 1
node.order = max((node.left).order,
(node.right).order) + 1
# make pair of assigned value and tree value
v[0].append([node.order, node.data])
# Function to print leaf nodes in
# the given order
def printLeafNodes(n, v):
# Sort the vector in increasing order of
# assigned node values
v=sorted(v[0])
for i in range(n - 1):
if (v[i][0]== v[i + 1][0]):
print(v[i][1], end = " ")
else:
print(v[i][1])
if (v[-1][0]== v[-2][0]):
print(v[-1][1], end = " ")
else:
print(v[-1][1])
# Driver Code
root = newNode(8, 0)
root.left = newNode(3, 0)
root.right = newNode(10, 0)
root.left.left = newNode(1, 0)
root.left.right = newNode(6, 0)
root.right.left = newNode(14, 0)
root.right.right = newNode(4, 0)
root.left.left.left = newNode(7, 0)
root.left.left.right = newNode(13, 0)
n = 9
v = [[] for i in range(1)]
Postorder(root, v)
printLeafNodes(n, v)
# This code is contributed by SHUBHAMSINGH10
Output4 6 7 13 14
1 10
3
8
Complexity Analysis:
- Time Complexity : O(nlogn)
- Auxiliary Space : O(n), where n is the number of nodes in the given Binary Tree.
We can also use Level Order Traversal to solve problem. We need to put an extra check inside the while loop that the node is printed only when both of its children are NULL. This would also work in O(n) time and O(n) auxiliary space.
Similar Reads
Print the nodes that are just above the leaf node Given a binary tree consisting of N nodes, the task is to print the nodes that are just above the leaf node.Examples: Input: N = 7, Below is the given Binary Tree: Output: 20 8 12 Explanation: Node 20 is just above the leaf node 22. Node 8 is just above the leaf node 4. Node 12 is just above the lea
8 min read
Print all leaf nodes of a binary tree from right to left Given a binary tree, the task is to print all the leaf nodes of the binary tree from right to left. Examples: Input : 1 / \ 2 3 / \ / \ 4 5 6 7 Output : 7 6 5 4 Input : 1 / \ 2 3 / \ \ 4 5 6 / / \ 7 8 9 Output : 9 8 7 4 Recursive Approach: Traverse the tree in Preorder fashion, by first processing t
14 min read
Print leftmost and rightmost nodes of a Binary Tree Given a Binary Tree, Print the corner nodes at each level. The node at the leftmost and the node at the rightmost. For example, the output for the following is 15, 10, 20, 8, 25. Recommended PracticeLeftmost and rightmost nodes of binary treeTry It! A Simple Solution is to do two traversals using th
7 min read
Print all nodes present in the subtree of a given node of a Binary Tree Given two arrays Node_ID[] and Parent_ID[]., construct a binary tree where value of ith node is equal to Node_ID[i] and parent of ith node is Parent_ID[i]. Given a node X, the task is to print node values of the tree rooted at X. Examples: Input: Node_ID[]= [11, 48, 100, 5], Parent_ID[] = [48, 0, 5,
11 min read
Print left and right leaf nodes separately in Binary Tree Given a binary tree, the task is to print left and right leaf nodes separately. Examples: Input: 0 / \ 1 2 / \ 3 4 Output: Left Leaf Nodes: 3 Right Leaf Nodes: 4 2 Input: 0 \ 1 \ 2 \ 3 Output: Left Leaf Nodes: None Right Leaf Nodes: 3 Approach: Check if given node is null. If null, then return from
8 min read