Given a binary tree, the task is to print left and right leaf nodes separately.
Input: 0 / \ 1 2 / \ 3 4 Output: Left Leaf Nodes: 3 Right Leaf Nodes: 4 2 Input: 0 \ 1 \ 2 \ 3 Output: Left Leaf Nodes: None Right Leaf Nodes: 3
- Check if given node is null. If null, then return from the function.
- For each traversal at right and left, send information about the child (left or right child) using the parameter type. Set type = 0 while descending to the left branch and set type = 1 for the right branch.
- Check if it is a leaf node. If the node is a leaf node, then store the leaf node in one of the two vectors of left and right child.
- If node is not a leaf node continue traversal.
- In the case of a single node tree, it will be both a root and a leaf node. This case has to be handled separately.
Below is the implementation of the above approach:
Left leaf nodes 3 Right leaf nodes 4 2
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 leaf nodes in binary tree from left to right using one stack
- Print all leaf nodes of a binary tree from right to left
- Print all leaf nodes of a Binary Tree from left to right
- 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
- Deepest left leaf node in a binary tree
- Deepest left leaf node in a binary tree | iterative approach
- Deepest right leaf node in a binary tree | Iterative approach
- Print all leaf nodes of an n-ary tree using DFS
- Remove all leaf nodes from a Generic Tree or N-ary Tree
- Program to count leaf nodes in a binary tree
- Pairwise Swap leaf nodes in a binary tree
- Count Non-Leaf nodes in a Binary Tree
- Leaf nodes from Preorder of a Binary Search Tree (Using Recursion)
- Product of all leaf nodes of binary tree
- Maximum sum of leaf nodes among all levels of the given 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 : princiraj1992