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 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:
- Check if the given node is null. If null, then return from the function.
- Check if it is a leaf node. If the node is a leaf node, then print its data.
- 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.
4 6 7 9 10
Time Complexity: O( n ) , where n is the number of nodes in the binary tree.
This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Print All Leaf Nodes of a Binary Tree from left to right | Set-2 ( Iterative Approach )
- Print all leaf nodes of a binary tree from right to left
- Print leaf nodes in binary tree from left to right using one stack
- Print left and right leaf nodes separately in Binary Tree
- Print the longest leaf to leaf path in a Binary tree
- Convert left-right representation of a binary tree to down-right
- Print Sum and Product of all Non-Leaf nodes in Binary Tree
- Print the nodes of binary tree as they become the leaf node
- Construct XOR tree by Given leaf nodes of Perfect Binary Tree
- Print all leaf nodes of an n-ary tree using DFS
- Remove all leaf nodes from a Generic Tree or N-ary Tree
- Deepest left leaf node in a binary tree
- Deepest left leaf node in a binary tree | iterative approach
- Sum of all leaf nodes of binary tree
- Product of all leaf nodes of binary tree
- Maximum sum of leaf nodes among all levels of the given binary tree
- Maximum sum of non-leaf nodes among all levels of the given binary tree
- Remove nodes from Binary Tree such that sum of all remaining root-to-leaf paths is atleast K
- Left-Right traversal of all the levels of Binary tree
- Deepest right leaf node in a binary tree | Iterative approach
Improved By : sanjeev2552