![]() |
VOOZH | about |
Given a binary tree, we need to print all leaf nodes of the given binary tree from left to right. That is, the nodes should be printed in the order they appear from left to right in the given tree.
For Example,
Input : Root of the below tree
👁 ImageOutput : 4 6 7 9 10
Corner Cases : For a tree with single node, the output should be the single node. And if root is null (empty tree), the output should be empty.
The idea to do this is similar to DFS algorithm. Below is a step by step algorithm to do this:
Below is the implementation of the above approach.
4 6 7 9 10
Time Complexity: O(n), where n is the number of nodes in the binary tree.
Auxiliary Space: O(h) where h is height of the binary tree
Create an empty queue and push the root node into the queue.
Do the following while the queue is not empty:
NULL, enqueue the left child into the queue.NULL, enqueue the right child into the queue.Below is the implementation of the above approach.
4 6 7 9 10
Time Complexity: O(n), where n is the number of nodes in the binary tree.
Auxiliary Space: O(n)