VOOZH about

URL: https://www.geeksforgeeks.org/dsa/remove-all-leaf-nodes-from-a-generic-tree-or-n-ary-tree/

⇱ Remove all leaf nodes from a Generic Tree or N-ary Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 15 Jul, 2025

Given an n-ary tree containing positive node values, the task is to delete all the leaf nodes from the tree and print preorder traversal of the tree after performing the deletion.
Note: An n-ary tree is a tree where each node can have zero or more children nodes. Unlike a binary tree, which has at most two children per node (left and right), the n-ary tree allows for multiple branches or children for each node.

 Examples:

Input:

πŸ‘ remove-all-leaf-nodes-from-a-generic-tree-or-n-ary-tree

Output: 1 2 4
Explanation: The leaf nodes (5, 3, and 6) are removed from the tree. After deletion, the tree structure is:

πŸ‘ remove-all-leaf-nodes-from-a-generic-tree-or-n-ary-tree-2

Approach:

The idea is to recursively traverse each node, deleting it if it’s a leaf(all childrens are NULL) by returning NULL. For non-leaf nodes, remove any leaf children by updating the children array and continue until all leaves are removed.

Below is the implementation of the above approach:


Output
1 2 4 

Time Complexity: O(n), where n is the number of nodes in the N-ary tree, as each node is visited once.
Auxiliary Space: O(h), where h is the height of the tree, due to the recursion stack during the deletion and traversal processes.

Comment
Article Tags: