Print left and right leaf nodes separately in Binary Tree
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
My Personal Notes arrow_drop_up