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 right to left
- Print all leaf nodes of a Binary Tree from left to right
- 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
- Iterative Method To Print Left View of a Binary Tree
- Print Sum and Product of all Non-Leaf nodes in Binary Tree
- Print the nodes of binary tree as they become the leaf node
- Check for Symmetric Binary Tree (Iterative Approach)
- Get level of a node in binary tree | iterative approach
- Construct Binary Tree from given Parent Array representation | Iterative Approach
- Iterative approach to check if a Binary Tree is Perfect
- Iterative approach to check for children sum property in a Binary Tree
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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.