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:
Output: 1 2 4 Explanation: The leaf nodes (5, 3, and 6) are removed from the tree. After deletion, the tree structure is:
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:
C++
// C++ Code to delete all leaf nodes in // an N-ary tree#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;vector<Node*>children;Node(intval){data=val;}};// Recursive function to delete all leaf nodesNode*deleteLeafNodes(Node*root){// If the root is NULL, return NULLif(!root){returnnullptr;}// If the node itself is a leaf,// delete itif(root->children.empty()){deleteroot;returnnullptr;}// Process children and remove// any leaf nodesfor(autoit=root->children.begin();it!=root->children.end();){if(*it&&(*it)->children.empty()){delete*it;it=root->children.erase(it);}else{*it=deleteLeafNodes(*it);++it;}}returnroot;}// Recursive function for preorder traversal// of the N-ary treevoidpreorderTraversal(Node*root){if(!root){return;}cout<<root->data<<" ";for(autochild:root->children){preorderTraversal(child);}}intmain(){// Representation of given N-ary tree// 1// / | \ // 2 3 4// / \ // 5 6Node*root=newNode(1);root->children.push_back(newNode(2));root->children.push_back(newNode(3));root->children.push_back(newNode(4));root->children[0]->children.push_back(newNode(5));root->children[2]->children.push_back(newNode(6));root=deleteLeafNodes(root);preorderTraversal(root);return0;}
Java
// Java Code to delete all leaf nodes in// an N-ary treeimportjava.util.ArrayList;importjava.util.Iterator;classNode{intdata;ArrayList<Node>children;Node(intval){data=val;children=newArrayList<>();}}classGfG{// Recursive function to delete all leaf nodesstaticNodedeleteLeafNodes(Noderoot){// If the root is NULL, return NULLif(root==null){returnnull;}// If the node itself is a leaf, delete itif(root.children.isEmpty()){returnnull;}// Process children and remove// any leaf nodesIterator<Node>it=root.children.iterator();while(it.hasNext()){Nodechild=it.next();if(child!=null&&child.children.isEmpty()){it.remove();}else{deleteLeafNodes(child);}}returnroot;}// Recursive function for preorder traversal// of the N-ary treestaticvoidpreorderTraversal(Noderoot){if(root==null){return;}System.out.print(root.data+" ");for(Nodechild:root.children){preorderTraversal(child);}}publicstaticvoidmain(String[]args){// Representation of given N-ary tree// 1// / | \// 2 3 4// / \// 5 6Noderoot=newNode(1);root.children.add(newNode(2));root.children.add(newNode(3));root.children.add(newNode(4));root.children.get(0).children.add(newNode(5));root.children.get(2).children.add(newNode(6));root=deleteLeafNodes(root);preorderTraversal(root);}}
Python
# Python Code to delete all leaf# nodes in an N-ary treeclassNode:def__init__(self,val):self.data=valself.children=[]# Recursive function to delete# all leaf nodesdefdelete_leaf_nodes(root):# If the root is None, # return Noneifnotroot:returnNone# If the node itself is a # leaf, delete itifnotroot.children:returnNone# Process children and remove # any leaf nodesroot.children=[delete_leaf_nodes(child)forchildinroot.childrenifchildandchild.children]returnroot# Recursive function for preorder traversal# of the N-ary treedefpreorder_traversal(root):ifnotroot:returnprint(root.data,end=" ")forchildinroot.children:preorder_traversal(child)if__name__=="__main__":# Representation of given N-ary tree# 1# / | \# 2 3 4# / \# 5 6root=Node(1)root.children.append(Node(2))root.children.append(Node(3))root.children.append(Node(4))root.children[0].children.append(Node(5))root.children[2].children.append(Node(6))root=delete_leaf_nodes(root)preorder_traversal(root)
C#
// C# Code to delete all leaf nodes in // an N-ary treeusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicList<Node>children;publicNode(intval){data=val;children=newList<Node>();}}classGfG{// Recursive function to delete all leaf nodesstaticNodeDeleteLeafNodes(Noderoot){// If the root is null, return nullif(root==null){returnnull;}// If the node itself is a leaf, // delete itif(root.children.Count==0){returnnull;}// Process children and remove // any leaf nodesroot.children.RemoveAll(child=>child!=null&&child.children.Count==0);for(inti=0;i<root.children.Count;i++){root.children[i]=DeleteLeafNodes(root.children[i]);}returnroot;}// Recursive function for preorder traversal// of the N-ary treestaticvoidpreorderTraversal(Noderoot){if(root==null){return;}Console.Write(root.data+" ");foreach(varchildinroot.children){preorderTraversal(child);}}staticvoidMain(string[]args){// Representation of given N-ary tree// 1// / | \// 2 3 4// / \// 5 6Noderoot=newNode(1);root.children.Add(newNode(2));root.children.Add(newNode(3));root.children.Add(newNode(4));root.children[0].children.Add(newNode(5));root.children[2].children.Add(newNode(6));root=DeleteLeafNodes(root);preorderTraversal(root);}}
JavaScript
// JavaScript Code to delete all leaf nodes// in an N-ary treeclassNode{constructor(val){this.data=val;this.children=[];}}// Recursive function to delete all leaf nodesfunctiondeleteLeafNodes(root){// If the root is null, return nullif(!root){returnnull;}// If the node itself is a leaf, delete itif(root.children.length===0){returnnull;}// Process children and remove any leaf nodesroot.children=root.children.filter(child=>{if(child&&child.children.length===0){returnfalse;// Remove this child}// Recur for non-leaf childrenchild=deleteLeafNodes(child);returnchild!==null;});returnroot;}// Recursive function for preorder traversal// of the N-ary treefunctionpreorderTraversal(root){if(!root){return;}console.log(root.data);for(constchildofroot.children){preorderTraversal(child);}}// Representation of given N-ary tree// 1// / | \// 2 3 4// / \// 5 6constroot=newNode(1);root.children.push(newNode(2));root.children.push(newNode(3));root.children.push(newNode(4));root.children[0].children.push(newNode(5));root.children[2].children.push(newNode(6));deleteLeafNodes(root);preorderTraversal(root);
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.