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
- Deepest left leaf node in a binary tree | iterative approach
- Print all leaf nodes of a Binary Tree from left to right
- Print leaf nodes in binary tree from left to right using one stack
- Deepest right leaf node in a binary tree | Iterative approach
- Sum of nodes at maximum depth of a Binary Tree | Iterative Approach
- Iterative program to count leaf nodes in a Binary Tree
- 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 whether a binary tree is a full binary tree or not | Iterative Approach
- Largest value in each level of Binary Tree | Set-2 (Iterative Approach)
- Check for Symmetric Binary Tree (Iterative Approach)
- Get level of a node in binary tree | iterative approach
- Print the longest leaf to leaf path in a Binary tree
- Deepest left leaf node 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 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.
Improved By : rituraj_jain