Given a Generic tree, the task is to delete the leaf nodes from the tree.

** Examples:**

Input: 
              5
          /  /  \  \
         1   2   3   8
        /   / \   \
       15  4   5   6 

Output:  
5 : 1 2 3
1 :
2 :
3 :

Explanation: 
Deleted leafs are:
8, 15, 4, 5, 6

Input:      
              8
         /    |    \
       9      7       2
     / | \    |    / / | \ \
    4  5 6    10  11 1 2  2 3
Output:  
8: 9 7 2
9:
7:
2:

**Approach: **Follow the steps given below to solve the problem

  • Take tree into the vector.
  • Traverse the tree and check the condition:
  • If current node is leaf then
  • Delete the leaf from vector
  • Else
  • Recursively call for every child.

Below is the implementation of the above approach:

#data structures #recursion #tree #n-ary-tree #tree-traversal #data analysis

Remove all leaf nodes from a Generic Tree or N-ary Tree
26.60 GEEK