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, output will be as shown below:
4 6 7 9 10
The idea to do this is similar to DFS algorithm. Below is step by step algorithm to do this:
- Check if 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 above step, node is not a leaf node then check if left and right childs of node exists. If yes then call function for left and right childs of the node recursively.
Below is C++ implementation of above approach.
4 6 7 9 10
Time Complexity: O( n ) , where n is 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 email@example.com. 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.
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Print all leaf nodes of a binary tree from right to left
- Print left and right leaf nodes separately in Binary Tree
- Print leaf nodes in binary tree from left to right using one stack
- Print All Leaf Nodes of a Binary Tree from left to right | Set-2 ( Iterative Approach )
- Print Sum and Product of all Non-Leaf nodes in Binary Tree
- Print the nodes of binary tree as they become the leaf node
- Print the longest leaf to leaf path in a Binary tree
- Deepest left leaf node in a binary tree
- Print all leaf nodes of an n-ary tree using DFS
- Deepest left leaf node in a binary tree | iterative approach
- Construct XOR tree by Given leaf nodes of Perfect Binary Tree
- Sum of all leaf nodes of binary tree
- Count Non-Leaf nodes in a Binary Tree
- Product of all leaf nodes of binary tree
- Pairwise Swap leaf nodes in a binary tree