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 Sum and Product of all Non-Leaf nodes in Binary Tree
- Print all leaf nodes of a Binary Tree from left to right
- Print all nodes that are at distance k from a leaf node
- Number of leaf nodes in the subtree of every node of an n-ary tree
- Print the longest leaf to leaf path in a Binary tree
- Closest leaf to a given node in Binary Tree
- Sum of all leaf nodes of binary tree
- Deepest left leaf node in a binary tree
- Product of all leaf nodes of binary tree
- Count Non-Leaf nodes in a Binary Tree
- Deepest right leaf node in a binary tree | Iterative approach
- Pairwise Swap leaf nodes in a binary tree
- Program to count leaf nodes in a binary tree
- Deepest left leaf node in a binary tree | iterative approach
- Iterative program to count leaf nodes 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 firstname.lastname@example.org. 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.