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.
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 problem using two stacks.
Approach:The idea is to use two stacks, one to store all the nodes of the tree and the other one to store all the leaf nodes. We will pop the top node of the first stack. If the node has a left child, we will push it on top of the first stack, if it has a right child then we will push it onto the top of the first stack, but if the node is a leaf node then we will push it onto the top of the second stack. We will do it for all the nodes until we have traversed the Binary tree completely.
Then we will start popping the second stack and print all its elements until the stack gets empty.
Below is the implementation of the above approach:
10 11 5 8
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
- Print all leaf nodes of a binary tree from right to left
- Deepest left leaf node in a binary tree | iterative approach
- Deepest right leaf node in a binary tree | Iterative approach
- Print leaf nodes in binary tree from left to right using one stack
- Print left and right leaf nodes separately in Binary Tree
- Check whether a binary tree is a full binary tree or not | Iterative Approach
- Iterative program to count leaf nodes in a Binary Tree
- Sum of nodes at maximum depth of a Binary Tree | Iterative Approach
- Print all nodes at distance K from given node: Iterative Approach
- 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
- Iterative Method To Print Left View of a 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
- Check for Symmetric Binary Tree (Iterative Approach)
- Get level of a node in binary tree | iterative approach
- Largest value in each level of Binary Tree | Set-2 (Iterative Approach)
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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.