Print all leaf nodes of a binary tree from right to left
Last Updated :
16 Mar, 2023
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 the root, then right subtree and then left subtree and do the following:
- Check if the root is null then return from the function.
- If it is a leaf node then print it.
- If not then check if it has right child, if yes then call function for right child of the node recursively.
- Check if it has left child, if yes then call function for left child of the node recursively.
Below is the implementation of the above approach:
C++
// C++ program to print leaf nodes from right to left
#include <iostream>
using namespace std;
// A Binary Tree Node
struct Node {
int data;
struct Node *left, *right;
};
// Utility function to create a new tree node
Node* newNode(int data)
{
Node* temp = new Node;
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// Function to print leaf
// nodes from right to left
void printLeafNodes(Node* root)
{
// If node is null, return
if (!root)
return;
// If node is leaf node, print its data
if (!root->left && !root->right) {
cout << root->data << " ";
return;
}
// If right child exists, check for leaf
// recursively
if (root->right)
printLeafNodes(root->right);
// If left child exists, check for leaf
// recursively
if (root->left)
printLeafNodes(root->left);
}
// Driver code
int main()
{
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
root->left->left->left = newNode(8);
root->right->right->left = newNode(9);
root->left->left->left->right = newNode(10);
printLeafNodes(root);
return 0;
}
Java
// Java program to print leaf nodes from right to left
import java.util.*;
class GFG
{
// A Binary Tree Node
static class Node
{
int data;
Node left, right;
};
// Utility function to create a new tree node
static Node newNode(int data)
{
Node temp = new Node();
temp.data = data;
temp.left = temp.right = null;
return temp;
}
// Function to print leaf
// nodes from right to left
static void printLeafNodes(Node root)
{
// If node is null, return
if (root == null)
return;
// If node is leaf node, print its data
if (root.left == null && root.right == null)
{
System.out.print( root.data +" ");
return;
}
// If right child exists, check for leaf
// recursively
if (root.right != null)
printLeafNodes(root.right);
// If left child exists, check for leaf
// recursively
if (root.left != null)
printLeafNodes(root.left);
}
// Driver code
public static void main(String args[])
{
Node root = newNode(1);
root.left = newNode(2);
root.right = newNode(3);
root.left.left = newNode(4);
root.left.right = newNode(5);
root.right.left = newNode(6);
root.right.right = newNode(7);
root.left.left.left = newNode(8);
root.right.right.left = newNode(9);
root.left.left.left.right = newNode(10);
printLeafNodes(root);
}
}
// This code is contributed by Arnab Kundu
Python3
# Python3 program to print
# leaf nodes from right to left
# Binary tree node
class newNode:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Function to print leaf
# nodes from right to left
def printLeafNodes(root):
# If node is null, return
if root == None:
return
# If node is leaf node,
# print its data
if (root.left == None and
root.right == None):
print(root.data, end = " ")
return
# If right child exists,
# check for leaf recursively
if root.right:
printLeafNodes(root.right)
# If left child exists,
# check for leaf recursively
if root.left:
printLeafNodes(root.left)
# Driver code
root = newNode(1)
root.left = newNode(2)
root.right = newNode(3)
root.left.left = newNode(4)
root.left.right = newNode(5)
root.right.left = newNode(6)
root.right.right = newNode(7)
root.left.left.left = newNode(8)
root.right.right.left = newNode(9)
root.left.left.left.right = newNode(10)
printLeafNodes(root)
# This code is contributed by SHUBHAMSINGH10
C#
using System;
// C# program to print leaf nodes from right to left
class GFG
{
// A Binary Tree Node
public class Node
{
public int data;
public Node left, right;
}
// Utility function to create a new tree node
public static Node newNode(int data)
{
Node temp = new Node();
temp.data = data;
temp.left = temp.right = null;
return temp;
}
// Function to print leaf
// nodes from right to left
public static void printLeafNodes(Node root)
{
// If node is null, return
if (root == null)
{
return;
}
// If node is leaf node, print its data
if (root.left == null && root.right == null)
{
Console.Write(root.data + " ");
return;
}
// If right child exists, check for leaf
// recursively
if (root.right != null)
{
printLeafNodes(root.right);
}
// If left child exists, check for leaf
// recursively
if (root.left != null)
{
printLeafNodes(root.left);
}
}
// Driver code
public static void Main(string[] args)
{
Node root = newNode(1);
root.left = newNode(2);
root.right = newNode(3);
root.left.left = newNode(4);
root.left.right = newNode(5);
root.right.left = newNode(6);
root.right.right = newNode(7);
root.left.left.left = newNode(8);
root.right.right.left = newNode(9);
root.left.left.left.right = newNode(10);
printLeafNodes(root);
}
}
// This code is contributed by shrikanth13
JavaScript
<script>
// JavaScript program to print leaf nodes from right to left
// A Binary Tree Node
class Node
{
constructor()
{
this.data = 0;
this.right = null;
this.left = null;
}
}
// Utility function to create a new tree node
function newNode(data)
{
var temp = new Node();
temp.data = data;
temp.left = temp.right = null;
return temp;
}
// Function to print leaf
// nodes from right to left
function printLeafNodes(root)
{
// If node is null, return
if (root == null)
{
return;
}
// If node is leaf node, print its data
if (root.left == null && root.right == null)
{
document.write(root.data + " ");
return;
}
// If right child exists, check for leaf
// recursively
if (root.right != null)
{
printLeafNodes(root.right);
}
// If left child exists, check for leaf
// recursively
if (root.left != null)
{
printLeafNodes(root.left);
}
}
// Driver code
var root = newNode(1);
root.left = newNode(2);
root.right = newNode(3);
root.left.left = newNode(4);
root.left.right = newNode(5);
root.right.left = newNode(6);
root.right.right = newNode(7);
root.left.left.left = newNode(8);
root.right.right.left = newNode(9);
root.left.left.left.right = newNode(10);
printLeafNodes(root);
</script>
Time Complexity: O(N) where N is the number of nodes in given binary tree.
Space Complexity: O(h) where h is the height of binary tree due to recursion.
Iterative Approach: The idea is to perform iterative Postorder traversal using one stack, but in a modified manner, first, we will visit the right subtree and then the left subtree and finally the root node and print the leaf nodes.
Efficient Approach:
- Create a stack 's' to store the nodes.
- Start from the root node and push it onto the stack.
- Traverse to the right child of the current node until it is not null, and push each node onto the stack.
- If the current node's left child is null, pop the top node from the stack and check if its right child is also null, then print the value of the node.
- If the left child of the top node on the stack is not null, then traverse to its left child and push each node onto the stack until it is not null.
- If the stack is empty, terminate the loop.
- Repeat steps 4 to 6 until the stack is empty.
Below is the implementation of the above approach:
C++
// C++ program to print leaf nodes from
// right to left using one stack
#include<bits/stdc++.h>
using namespace std;
// Structure of binary tree
struct Node {
Node* left;
Node* right;
int data;
};
// Function to create a new node
Node* newNode(int key)
{
Node* node = new Node();
node->left = node->right = NULL;
node->data = key;
return node;
}
// Function to Print all the leaf nodes
// of Binary tree using one stack
void printLeafRightToLeft(Node* p)
{
// stack to store the nodes
stack<Node*> s;
while (1) {
// If p is not null then push
// it on the stack
if (p) {
s.push(p);
p = p->right;
}
else {
// If stack is empty then come out
// of the loop
if (s.empty())
break;
else {
// If the node on top of the stack has its
// left subtree as null then pop that node and
// print the node only if its right
// subtree is also null
if (s.top()->left == NULL) {
p = s.top();
s.pop();
// Print the leaf node
if (p->right == NULL)
printf("%d ", p->data);
}
while (p == s.top()->left) {
p = s.top();
s.pop();
if (s.empty())
break;
}
// If stack is not empty then assign p as
// the stack's top node's left child
if (!s.empty())
p = s.top()->left;
else
p = NULL;
}
}
}
}
// Driver Code
int main()
{
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
printLeafRightToLeft(root);
return 0;
}
Java
// Java program to print leaf nodes from
// right to left using one stack
import java.util.Stack;
class GFG
{
// Structure of binary tree
static class Node
{
Node left;
Node right;
int data;
};
// Function to create a new node
static Node newNode(int key)
{
Node node = new Node();
node.left = node.right = null;
node.data = key;
return node;
}
// Function to Print all the leaf nodes
// of Binary tree using one stack
static void printLeafRightToLeft(Node p)
{
// stack to store the nodes
Stack<Node> s = new Stack<>();
while (true)
{
// If p is not null then push
// it on the stack
if (p != null)
{
s.push(p);
p = p.right;
}
else
{
// If stack is empty then come out
// of the loop
if (s.empty())
break;
else
{
// If the node on top of the stack has its
// left subtree as null then pop that node and
// print the node only if its right
// subtree is also null
if (s.peek().left == null)
{
p = s.peek();
s.pop();
// Print the leaf node
if (p.right == null)
System.out.print( p.data+" ");
}
while (p == s.peek().left)
{
p = s.peek();
s.pop();
if (s.empty())
break;
}
// If stack is not empty then assign p as
// the stack's top node's left child
if (!s.empty())
p = s.peek().left;
else
p = null;
}
}
}
}
// Driver Code
public static void main(String[] args)
{
Node root = newNode(1);
root.left = newNode(2);
root.right = newNode(3);
root.left.left = newNode(4);
root.left.right = newNode(5);
root.right.left = newNode(6);
root.right.right = newNode(7);
printLeafRightToLeft(root);
}
}
// This code is contributed by 29AjayKumar
Python3
# Python3 program to print leaf nodes
# from right to left using one stack
# Tree node
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Function to create a new node
def newNode(key) :
node = Node(0)
node.left = node.right = None
node.data = key
return node
# Function to Print all the leaf nodes
# of Binary tree using one stack
def printLeafRightToLeft(p) :
# stack to store the nodes
s = []
while (True) :
# If p is not None then append
# it on the stack
if (p != None) :
s.append(p)
p = p.right
else:
# If stack is len then come out
# of the loop
if (len(s) == 0) :
break
else:
# If the node on top of the stack has
# its left subtree as None then pop
# that node and print the node only
# if its right subtree is also None
if (s[-1].left == None) :
p = s[-1]
s.pop()
# Print the leaf node
if (p.right == None) :
print( p.data, end = " ")
while (p == s[-1].left) :
p = s[-1]
s.pop()
if (len(s) == 0) :
break
# If stack is not len then assign p as
# the stack's top node's left child
if (len(s) > 0) :
p = s[-1].left
else:
p = None
# Driver Code
root = newNode(1)
root.left = newNode(2)
root.right = newNode(3)
root.left.left = newNode(4)
root.left.right = newNode(5)
root.right.left = newNode(6)
root.right.right = newNode(7)
printLeafRightToLeft(root)
# This code is contributed by Arnab Kundu
C#
// C# program to print leaf nodes from
// right to left using one stack
using System;
using System.Collections.Generic;
class GFG
{
// Structure of binary tree
public class Node
{
public Node left;
public Node right;
public int data;
};
// Function to create a new node
static Node newNode(int key)
{
Node node = new Node();
node.left = node.right = null;
node.data = key;
return node;
}
// Function to Print all the leaf nodes
// of Binary tree using one stack
static void printLeafRightToLeft(Node p)
{
// stack to store the nodes
Stack<Node> s = new Stack<Node>();
while (true)
{
// If p is not null then push
// it on the stack
if (p != null)
{
s.Push(p);
p = p.right;
}
else
{
// If stack is empty then come out
// of the loop
if (s.Count == 0)
break;
else
{
// If the node on top of the stack has its
// left subtree as null then pop that node and
// print the node only if its right
// subtree is also null
if (s.Peek().left == null)
{
p = s.Peek();
s.Pop();
// Print the leaf node
if (p.right == null)
Console.Write(p.data + " ");
}
while (p == s.Peek().left)
{
p = s.Peek();
s.Pop();
if (s.Count == 0)
break;
}
// If stack is not empty then assign p as
// the stack's top node's left child
if (s.Count != 0)
p = s.Peek().left;
else
p = null;
}
}
}
}
// Driver Code
public static void Main(String[] args)
{
Node root = newNode(1);
root.left = newNode(2);
root.right = newNode(3);
root.left.left = newNode(4);
root.left.right = newNode(5);
root.right.left = newNode(6);
root.right.right = newNode(7);
printLeafRightToLeft(root);
}
}
// This code contributed by Rajput-Ji
JavaScript
<script>
// Javascript program to print leaf nodes from
// right to left using one stack
// Structure of binary tree
class Node
{
constructor()
{
this.left = null;
this.right = null;
this.data = 0;
}
};
// Function to create a new node
function newNode(key)
{
var node = new Node();
node.left = node.right = null;
node.data = key;
return node;
}
// Function to Print all the leaf nodes
// of Binary tree using one stack
function printLeafRightToLeft(p)
{
// Stack to store the nodes
var s = [];
while (true)
{
// If p is not null then push
// it on the stack
if (p != null)
{
s.push(p);
p = p.right;
}
else
{
// If stack is empty then come out
// of the loop
if (s.length == 0)
break;
else
{
// If the node on top of the stack has
// its left subtree as null then pop
// that node and print the node only
// if its right subtree is also null
if (s[s.length - 1].left == null)
{
p = s[s.length - 1];
s.pop();
// Print the leaf node
if (p.right == null)
document.write(p.data + " ");
}
while (p == s[s.length - 1].left)
{
p = s[s.length - 1];
s.pop();
if (s.length == 0)
break;
}
// If stack is not empty then assign p as
// the stack's top node's left child
if (s.length != 0)
p = s[s.length - 1].left;
else
p = null;
}
}
}
}
// Driver Code
var root = newNode(1);
root.left = newNode(2);
root.right = newNode(3);
root.left.left = newNode(4);
root.left.right = newNode(5);
root.right.left = newNode(6);
root.right.right = newNode(7);
printLeafRightToLeft(root);
// This code is contributed by rrrtnx
</script>
Time Complexity: O(N), where N is the total number of nodes in the binary tree.
Auxiliary Space: O(N)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem