VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-leaf-nodes-left-right-binary-tree/

⇱ All Leaves of a Binary Tree - Print in Order - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

All Leaves of a Binary Tree - Print in Order

Last Updated : 22 Jan, 2026

Given a binary tree, we need 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, 

Input : Root of the below tree

👁 Image

Output : 4 6 7 9 10

Corner Cases : For a tree with single node, the output should be the single node. And if root is null (empty tree), the output should be empty.

Using DFS :

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. 


Output
4 6 7 9 10 

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

Using BFS:

Create an empty queue and push the root node into the queue.

Do the following while the queue is not empty:

  1. Remove (dequeue) the front node from the queue.
  2. If the node is a leaf node, print its data.
  3. Else:
    • If the left child is not NULL, enqueue the left child into the queue.
    • If the right child is not NULL, enqueue the right child into the queue.

Below is the implementation of the above approach. 


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)

Comment