The Wayback Machine - https://web.archive.org/web/20240530053034/https://www.geeksforgeeks.org/print-leaf-nodes-left-right-binary-tree/
Open In App

Print all leaf nodes of a Binary Tree from left to right

Last Updated : 21 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a binary tree, we need to write a program to print all leaf nodes of the given binary tree from left to right. That is, the nodes should be printed in the order they appear from left to right in the given tree. 

For Example, 

For the above binary tree, the output will be as shown below: 

4 6 7 9 10

The idea to do this is similar to DFS algorithm. Below is a step by step algorithm to do this: 

  1. Check if the given node is null. If null, then return from the function.
  2. Check if it is a leaf node. If the node is a leaf node, then print its data.
  3. If in the above step, the node is not a leaf node then check if the left and right children of node exist. If yes then call the function for left and right child of the node recursively.

Below is the implementation of the above approach. 

C++




/* C++ program to print leaf nodes from left
   to right */
#include <iostream>
using namespace std;
  
// A Binary Tree Node
struct Node
{
    int data;
    struct Node *left, *right;
};
 
// function to print leaf
// nodes from left to right
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 left child exists, check for leaf
    // recursively
    if (root->left)
       printLeafNodes(root->left);
         
    // if right child exists, check for leaf
    // recursively
    if (root->right)
       printLeafNodes(root->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;
}
  
// Driver program to test above functions
int main()
{
    // Let us create binary tree shown in
    // above diagram
    Node *root = newNode(1);
    root->left = newNode(2);
    root->right = newNode(3);
    root->left->left = newNode(4);
    root->right->left = newNode(5);
    root->right->right = newNode(8);
    root->right->left->left = newNode(6);
    root->right->left->right = newNode(7);
    root->right->right->left = newNode(9);
    root->right->right->right = newNode(10);
  
    // print leaf nodes of the given tree
    printLeafNodes(root);
     
    return 0;
}


Java




// Java program to print leaf nodes
// from left to right
import java.util.*;
   
class GFG{
      
// A Binary Tree Node
static class Node
{
    public int data;
    public Node left, right;
};
  
// Function to print leaf
// nodes from left to right
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 left child exists, check for leaf
    // recursively
    if (root.left != null)
        printLeafNodes(root.left);
          
    // If right child exists, check for leaf
    // recursively
    if (root.right != null)
        printLeafNodes(root.right);
}
  
// Utility function to create a new tree node
static Node newNode(int data)
{
    Node temp = new Node();
    temp.data = data;
    temp.left = null;
    temp.right = null;
    return temp;
}
  
// Driver code
public static void main(String []args)
{
      
    // Let us create binary tree shown in
    // above diagram
    Node root = newNode(1);
    root.left = newNode(2);
    root.right = newNode(3);
    root.left.left = newNode(4);
    root.right.left = newNode(5);
    root.right.right = newNode(8);
    root.right.left.left = newNode(6);
    root.right.left.right = newNode(7);
    root.right.right.left = newNode(9);
    root.right.right.right = newNode(10);
  
    // Print leaf nodes of the given tree
    printLeafNodes(root);
}
}
 
// This code is contributed by pratham76


Python3




# Python3 program to print
# leaf nodes from left to right
 
# Binary tree node
class Node:
   
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
 
# Function to print leaf
# nodes from left to right
def printLeafNodes(root: Node) -> None:
 
    # If node is null, return
    if (not root):
        return
 
    # If node is leaf node,
    # print its data
    if (not root.left and
        not root.right):
        print(root.data,
              end = " ")
        return
 
    # If left child exists,
    # check for leaf recursively
    if root.left:
        printLeafNodes(root.left)
 
    # If right child exists,
    # check for leaf recursively
    if root.right:
        printLeafNodes(root.right)
 
# Driver Code
if __name__ == "__main__":
 
    # Let us create binary tree shown in
    # above diagram
    root = Node(1)
    root.left = Node(2)
    root.right = Node(3)
    root.left.left = Node(4)
    root.right.left = Node(5)
    root.right.right = Node(8)
    root.right.left.left = Node(6)
    root.right.left.right = Node(7)
    root.right.right.left = Node(9)
    root.right.right.right = Node(10)
 
    # print leaf nodes of the given tree
    printLeafNodes(root)
 
# This code is contributed by sanjeev2552


C#




// C# program to print leaf nodes
// from left to right
using System;
  
class GFG{
     
// A Binary Tree Node
class Node
{
    public int data;
    public Node left, right;
};
 
// Function to print leaf
// nodes from left to right
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 left child exists, check for leaf
    // recursively
    if (root.left != null)
        printLeafNodes(root.left);
         
    // If right child exists, check for leaf
    // recursively
    if (root.right != null)
        printLeafNodes(root.right);
}
 
// Utility function to create a new tree node
static Node newNode(int data)
{
    Node temp = new Node();
    temp.data = data;
    temp.left = null;
    temp.right = null;
    return temp;
}
 
// Driver code
public static void Main()
{
     
    // Let us create binary tree shown in
    // above diagram
    Node root = newNode(1);
    root.left = newNode(2);
    root.right = newNode(3);
    root.left.left = newNode(4);
    root.right.left = newNode(5);
    root.right.right = newNode(8);
    root.right.left.left = newNode(6);
    root.right.left.right = newNode(7);
    root.right.right.left = newNode(9);
    root.right.right.right = newNode(10);
 
    // Print leaf nodes of the given tree
    printLeafNodes(root);
}
}
 
// This code is contributed by rutvik_56


Javascript




<script>
 
// Javascript program to print leaf nodes
// from left to right
 
// A Binary Tree Node
class Node
{
    constructor()
    {
        this.data = 0;
        this.left = null;
        this.right = null;
    }
};
 
// Function to print leaf
// nodes from left to right
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 left child exists, check for leaf
    // recursively
    if (root.left != null)
        printLeafNodes(root.left);
         
    // If right child exists, check for leaf
    // recursively
    if (root.right != null)
        printLeafNodes(root.right);
}
 
// Utility function to create a new tree node
function newNode(data)
{
    var temp = new Node();
    temp.data = data;
    temp.left = null;
    temp.right = null;
    return temp;
}
 
// Driver code
 
// Let us create binary tree shown in
// above diagram
var root = newNode(1);
root.left = newNode(2);
root.right = newNode(3);
root.left.left = newNode(4);
root.right.left = newNode(5);
root.right.right = newNode(8);
root.right.left.left = newNode(6);
root.right.left.right = newNode(7);
root.right.right.left = newNode(9);
root.right.right.right = newNode(10);
 
// Print leaf nodes of the given tree
printLeafNodes(root);
 
// This code is contributed by rrrtnx
 
</script>


Output

4 6 7 9 10 

Time Complexity: O(n), where n is the number of nodes in the binary tree. 
Auxiliary Space: O(n)

Iterative Method:

Following is a simple stack-based iterative method to print the leaf nodes from left to right.

  • Create an empty stack ‘st’ and push the root node to stack.
  • Do the following while stack is not empty.
    • Pop an item from the stack
    • If the node is a leaf node then print it.
    • Else:
      • If the right node is not NULL
        • push the right node into the stack
      • If the left node is not NULL
        • push the left node into the stack

Below is the implementation of the above approach. 

C++




// C++ program to print leaf nodes from left to right
#include <bits/stdc++.h>
using namespace std;
 
// A Binary Tree Node
struct Node {
    int data;
    struct Node *left, *right;
};
 
// fun to creates and returns a new node
Node* newNode(int data)
{
    Node* temp = new Node();
    temp->data = data;
    temp->left = temp->right = NULL;
    return temp;
}
 
// fun to print leaf nodes from left to right
void printleafNodes(Node* root)
{
    // base case
    if (!root)
        return;
 
    // implement iterative preorder traversal and start
    // storing leaf nodes.
    stack<Node*> st;
    st.push(root);
 
    while (!st.empty()) {
        root = st.top();
        st.pop();
 
        // if node is leafnode, print its data
        if (!root->left && !root->right)
            cout << root->data << " ";
 
        if (root->right)
            st.push(root->right);
        if (root->left)
            st.push(root->left);
    }
}
 
// Driver program to test above functions
int main()
{
 
    // create a binary tree
    Node* root = newNode(1);
    root->left = newNode(2);
    root->right = newNode(3);
      root->left->left = newNode(4);
    root->right->left = newNode(5);
    root->right->right = newNode(8);
    root->right->left->left = newNode(6);
    root->right->left->right = newNode(7);
    root->right->right->left = newNode(9);
    root->right->right->right = newNode(10);
 
    // prints leaf nodes of the given tree
    printleafNodes(root);
 
    return 0;
}
// This Method and code is contributed by Modem Upendra


Java




// Java program to print leaf nodes from left to right
import java.util.*;
 
public class GFG {
 
    // structure of node of Binary Tree
    static class Node {
        int data;
        Node left, right;
 
        Node(int item)
        {
            data = item;
            left = right = null;
        }
    }
 
    // fun to print leaf nodes from left to right
    static void printleafNodes(Node root)
    {
        // base case
        if (root == null)
            return;
 
        // implement iterative preorder traversal and start
        // storing leaf nodes.
        Stack<Node> st = new Stack<>();
        st.push(root);
 
        while (!st.isEmpty()) {
            root = st.peek();
            st.pop();
 
            // if node is leafnode, print its data
            if (root.left == null && root.right == null)
                System.out.print(root.data + " ");
 
            if (root.right != null)
                st.push(root.right);
            if (root.left != null)
                st.push(root.left);
        }
    }
 
    // Driver program to test above functions
    public static void main(String[] args)
    {
        // create a binary tree
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.left = new Node(4);
        root.right.left = new Node(5);
        root.right.right = new Node(8);
        root.right.left.left = new Node(6);
        root.right.left.right = new Node(7);
        root.right.right.left = new Node(9);
        root.right.right.right = new Node(10);
 
        // prints leaf nodes of the given tree
        printleafNodes(root);
    }
}
// This code is contributed by Karandeep1234


Python3




# Python3 program to print leaf nodes from left to right
 
# A Binary Tree Node
class Node:
 
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
 
# fun to creates and returns a new node
def newNode(data):
    temp = Node(data)
    return temp
 
# fun to print leaf nodes from left to right
def printleafNodes(root):
    # base case
    if not root:
        return
    # implement iterative preorder traversal and start
    # storing leaf nodes.
    st = []
    st.append(root)
 
    while len(st) > 0:
        root = st.pop()
 
        # if node is leafnode, print its data
        if not root.left and not root.right:
            print(root.data, end=" ")
 
        if root.right:
            st.append(root.right)
        if root.left:
            st.append(root.left)
 
# Driver program to test above functions
if __name__ == '__main__':
 
    # create a binary tree
    root = newNode(1)
    root.left = newNode(2)
    root.right = newNode(3)
    root.left.left = newNode(4)
    root.right.left = newNode(5)
    root.right.right = newNode(8)
    root.right.left.left = newNode(6)
    root.right.left.right = newNode(7)
    root.right.right.left = newNode(9)
    root.right.right.right = newNode(10)
 
    # prints leaf nodes of the given tree
    printleafNodes(root)
 
# This code is contributed by lokeshpotta20.


C#




using System;
using System.Collections.Generic;
 
class GFG {
  // structure of node of Binary Tree
  class Node {
    public int data;
    public Node left, right;
 
    public Node(int item)
    {
      data = item;
      left = right = null;
    }
  }
 
  // fun to print leaf nodes from left to right
  static void printleafNodes(Node root)
  {
    // base case
    if (root == null)
      return;
 
    // implement iterative preorder traversal and start
    // storing leaf nodes.
    Stack<Node> st = new Stack<Node>();
    st.Push(root);
 
    while (st.Count != 0) {
      root = st.Peek();
      st.Pop();
 
      // if node is leafnode, print its data
      if (root.left == null && root.right == null)
        Console.Write(root.data + " ");
 
      if (root.right != null)
        st.Push(root.right);
      if (root.left != null)
        st.Push(root.left);
    }
  }
 
  // Driver program to test above functions
  public static void Main(string[] args)
  {
    // create a binary tree
    Node root = new Node(1);
    root.left = new Node(2);
    root.right = new Node(3);
    root.left.left = new Node(4);
    root.right.left = new Node(5);
    root.right.right = new Node(8);
    root.right.left.left = new Node(6);
    root.right.left.right = new Node(7);
    root.right.right.left = new Node(9);
    root.right.right.right = new Node(10);
 
    // prints leaf nodes of the given tree
    printleafNodes(root);
  }
}
 
// This code is contributed by pradeepkumarppk2003


Javascript




// Javascript program to print leaf nodes from left to right
 
// A Binary Tree Node
class Node {
    constructor(data){
        this.data=data;
        this.left=null;
        this.right=null;
    }
}
 
// fun to print leaf nodes from left to right
function printleafNodes(root)
{
    // base case
    if (!root)
        return;
 
    // implement iterative preorder traversal and start
    // storing leaf nodes.
    let st=[];
    st.push(root);
 
    while (st.length>0) {
        root = st[st.length-1];
        st.pop();
 
        // if node is leafnode, print its data
        if (!root.left && !root.right)
            document.write(root.data + " ");
 
        if (root.right)
            st.push(root.right);
        if (root.left)
            st.push(root.left);
    }
}
 
// Driver program to test above functions
// create a binary tree
let root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.right.left = new Node(5);
root.right.right = new Node(8);
root.right.left.left = new Node(6);
root.right.left.right = new Node(7);
root.right.right.left = new Node(9);
root.right.right.right = new Node(10);
 
// prints leaf nodes of the given tree
printleafNodes(root);


Output

4 6 7 9 10 

Time Complexity: O(n), where n is the number of nodes in the binary tree. 
Auxiliary Space: O(n)



Similar Reads

Print All Leaf Nodes of a Binary Tree from left to right | Set-2 ( Iterative Approach )
Given a Binary Tree, the task is to print the leaf nodes from left to right. The nodes must be printed in the order they appear from left to right.Examples: Input : 1 / \ 2 3 / \ / \ 4 5 6 7 Output :4 5 6 7 Input : 4 / \ 5 9 / \ / \ 8 3 7 2 / / \ 12 6 1 Output :12 3 7 6 1 We have already discussed the Recursive approach. Here we will solve the prob
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 the root, then right subtree and then left subtree
14 min read
Print leaf nodes in binary tree from left to right using one stack
Given a binary tree, the task is to print all leaf nodes of the given binary tree from left to right. That is, the nodes should be printed in the order they appear from left to right in the given tree.Examples: Input : 1 / \ 2 3 / \ / \ 4 5 6 7 Output : 4 5 6 7 Input : 4 / \ 5 9 / \ / \ 8 3 7 2 / / \ 12 6 1 Output : 12 3 7 6 1 We have already discu
8 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 the function.For each traversal at right and left,
8 min read
Sum of Bitwise AND of the sum of all leaf and non-leaf nodes for each level of a Binary Tree
Given a Binary Tree consisting of N nodes, the task is to find the sum of Bitwise AND of the sum of all leaf nodes and the sum of all non-leaf nodes for each level in the given Tree. Examples: Input: Below is the given tree: 5 / \ 3 9 / \ 6 4 \ 7Output: 5Explanation: For Level 1: leaf node sum = 0, non-leaf node sum = 5. So, 0&amp;5 = 0. For Level
10 min read
Find the sum of all left leaf nodes which also has its right sibling
Given a Binary Tree rooted at root, the task is to find the sum of all leaf nodes which are left child of their parents and which also have their right sibling i.e, it's a parent has also a right child. Examples: Input: 16 / \ 20 15 / / \ 100 21 25 / / \ / \27 14 9 7 6 / \ \ 17 12 2Output: 24.Explanation: The leaf nodes having values 7 and 17 only
8 min read
Print a matrix in alternate manner (left to right then right to left)
Given a 2D array, the task is to print the 2D in alternate manner (First row from left to right, then from right to left, and so on). Examples: Input : arr[][2] = {{1, 2} {2, 3}}; Output : 1 2 3 2 Input :arr[][3] = { { 7 , 2 , 3 }, { 2 , 3 , 4 }, { 5 , 6 , 1 }}; Output : 7 2 3 4 3 2 5 6 1 The solution of this problem is that run two loops and print
5 min read
Print the longest leaf to leaf path in a Binary tree
C/C++ Code // C++ program to print the longest leaf to leaf // path #include &lt;bits/stdc++.h&gt; using namespace std; // Tree node structure used in the program struct Node { int data; Node *left, *right; }; struct Node* newNode(int data) { struct Node* node = new Node; node-&gt;data = data; node-&gt;left = node-&gt;right = NULL; return (node); }
28 min read
Print Sum and Product of all Non-Leaf nodes in Binary Tree
Given a Binary tree. The task is to find and print the product and sum of all internal nodes (non-leaf nodes) in the tree. In the above tree, only two nodes 1 and 2 are non-leaf nodes. Therefore, product of non-leaf nodes = 1 * 2 = 2. And sum of non-leaf nodes = 1 + 2 =3. Examples: Input : 1 / \ 2 3 / \ / \ 4 5 6 7 \ 8 Output : Product = 36, Sum =
8 min read
Convert left-right representation of a binary tree to down-right
Left-Right representation of a binary tree is standard representation where every node has a pointer to left child and another pointer to right child.Down-Right representation is an alternate representation where every node has a pointer to left (or first) child and another pointer to next sibling. So siblings at every level are connected from left
10 min read