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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Print the longest leaf to leaf path in a 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 | Set-2 ( Iterative Approach )
- Print leaf nodes in binary tree from left to right using one stack
- Print all leaf nodes of a binary tree from right to left
- Print left and right leaf nodes separately in Binary Tree
- Print all leaf nodes of a Binary Tree from left to right
- Construct XOR tree by Given leaf nodes of Perfect Binary Tree
- Print all nodes that are at distance k from a leaf node
- Print the nodes that are just above the 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
- Remove all leaf nodes from a Generic Tree or N-ary Tree
- Program to count leaf nodes in a binary tree
- Find height of a special binary tree whose leaf nodes are connected
- Iterative program to count leaf nodes in a Binary Tree
- Sum of all leaf nodes of binary tree
- Pairwise Swap leaf nodes in a binary tree
- Count Non-Leaf nodes in a Binary Tree
- Leaf nodes from Preorder of a Binary Search Tree (Using Recursion)
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.