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.
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.