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 left to right
- Print Sum and Product of all Non-Leaf nodes in Binary Tree
- Print all leaf nodes of a binary tree from right to left
- Print leaf nodes in binary tree from left to right using one stack
- Print left and right leaf nodes separately in Binary Tree
- Print All Leaf Nodes of a Binary Tree from left to right | Set-2 ( Iterative Approach )
- Print all nodes except rightmost node of every level of the Binary Tree
- Print all the nodes except the leftmost node in every level of the given binary tree
- Print the longest leaf to leaf path in a Binary tree
- 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 all leaf nodes of an n-ary tree using DFS
- Construct XOR tree by Given leaf nodes of Perfect Binary Tree
- Sum of all leaf nodes of binary tree
- Count Non-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.