Given a binary tree. First print all leaf nodes, after that remove all the leaf nodes from the tree and now print all the new formed leaf nodes and keep doing this until all the nodes are removed from the tree.
Input : 8 / \ 3 10 / \ / \ 1 6 14 4 / \ 7 13 Output : 4 6 7 13 14 1 10 3 8
Source :Flipkart On Campus Recruitment
Approach : The idea is to perform simple dfs and assign different values to each node on the basis of following conditions:
- Initially assign all the nodes with value as 0.
- Now, Assign all the nodes with the value as (maximum value of both child)+1.
Tree before DFS: A temporary value zero is assigned to all of the nodes.
Tree after DFS: Nodes are assigned with the value as (maximum value of both child)+1.
Now, you can see in the above tree that after all the values are assigned to each node, the task now reduces to print the tree on the basis of increasing order of node values assigned to them.
Below is the implementation of above approach:
4 6 7 13 14 1 10 3 8
Time Complexity : O(nlogn)
Auxiliary Space : O(n), where n is the number of nodes in the given Binary Tree.
- 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 Sum and Product of all Non-Leaf nodes in Binary Tree
- Print leaf nodes in binary tree from left to right using one stack
- Print All Leaf Nodes of a Binary Tree from left to right | Set-2 ( Iterative Approach )
- Print all the nodes except the leftmost node in every level of the given binary tree
- Print all nodes that are at distance k from a leaf node
- Print the longest leaf to leaf path in a Binary tree
- Number of leaf nodes in the subtree of every node of an n-ary tree
- Print all leaf nodes of an n-ary tree using DFS
- Sum of all leaf nodes of binary tree
- Closest leaf to a given node in Binary Tree
- Product of all leaf nodes of binary tree
- Count Non-Leaf nodes 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.