Open In App

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

Last Updated : 28 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

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:

C++
// C++ Code to delete all leaf nodes in 
// an N-ary tree
#include <bits/stdc++.h>
using namespace std;

class Node {
  public:
    int data;
    vector<Node *> children;

    Node(int val) {
        data = val;
    }
};

// Recursive function to delete all leaf nodes
Node *deleteLeafNodes(Node *root) {

    // If the root is NULL, return NULL
    if (!root) {
        return nullptr;
    }

    // If the node itself is a leaf,
    // delete it
    if (root->children.empty()) {
        delete root;
        return nullptr;
    }

    // Process children and remove
  	// any leaf nodes
    for (auto it = root->children.begin();
         it != root->children.end();) {

        if (*it && (*it)->children.empty()) {
            delete *it;
            it = root->children.erase(it);
        }
        else {
            *it = deleteLeafNodes(*it);
            ++it;
        }
    }

    return root;
}

// Recursive function for preorder traversal
// of the N-ary tree
void preorderTraversal(Node *root) {

    if (!root) {
        return;
    }

    cout << root->data << " ";
    for (auto child : root->children) {
        preorderTraversal(child);
    }
}

int main() {

    // Representation of given N-ary tree
    //         1
    //       / | \
    //     2   3   4
    //    /         \
    //   5           6
    Node *root = new Node(1);
    root->children.push_back(new Node(2));
    root->children.push_back(new Node(3));
    root->children.push_back(new Node(4));
    root->children[0]->children.push_back(new Node(5));
    root->children[2]->children.push_back(new Node(6));

    root = deleteLeafNodes(root);

    preorderTraversal(root);

    return 0;
}
Java
// Java Code to delete all leaf nodes in
// an N-ary tree
import java.util.ArrayList;
import java.util.Iterator;

class Node {
    int data;
    ArrayList<Node> children;

    Node(int val) {
        data = val;
        children = new ArrayList<>();
    }
}

class GfG {

    // Recursive function to delete all leaf nodes
    static Node deleteLeafNodes(Node root) {

        // If the root is NULL, return NULL
        if (root == null) {
            return null;
        }

        // If the node itself is a leaf, delete it
        if (root.children.isEmpty()) {
            return null;
        }

        // Process children and remove
      	// any leaf nodes
        Iterator<Node> it = root.children.iterator();
        while (it.hasNext()) {
            Node child = it.next();
            if (child != null && child.children.isEmpty()) {
                it.remove();
            }
            else {
                deleteLeafNodes(child);
            }
        }

        return root;
    }

    // Recursive function for preorder traversal
    // of the N-ary tree
    static void preorderTraversal(Node root) {

        if (root == null) {
            return;
        }

        System.out.print(root.data + " ");
        for (Node child : root.children) {
            preorderTraversal(child);
        }
    }

    public static void main(String[] args) {

        // Representation of given N-ary tree
        //         1
        //       / | \
        //     2   3   4
        //    /         \
        //   5           6
        Node root = new Node(1);
        root.children.add(new Node(2));
        root.children.add(new Node(3));
        root.children.add(new Node(4));
        root.children.get(0).children.add(new Node(5));
        root.children.get(2).children.add(new Node(6));

        root = deleteLeafNodes(root);
        preorderTraversal(root);
    }
}
Python
# Python Code to delete all leaf
# nodes in an N-ary tree
class Node:
    def __init__(self, val):
        self.data = val
        self.children = []

# Recursive function to delete
# all leaf nodes
def delete_leaf_nodes(root):

    # If the root is None, 
    # return None
    if not root:
        return None

    # If the node itself is a 
    # leaf, delete it
    if not root.children:
        return None

    # Process children and remove 
    # any leaf nodes
    root.children = [delete_leaf_nodes(child)
                     for child in root.children
                     if child and child.children]

    return root

# Recursive function for preorder traversal
# of the N-ary tree
def preorder_traversal(root):

    if not root:
        return

    print(root.data, end=" ")
    for child in root.children:
        preorder_traversal(child)


if __name__ == "__main__":

    # Representation of given N-ary tree
    #         1
    #       / | \
    #     2   3   4
    #    /         \
    #   5           6
    root = 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 tree
using System;
using System.Collections.Generic;

class Node {
    public int data;
    public List<Node> children;

    public Node(int val) {
        data = val;
        children = new List<Node>();
    }
}

class GfG {

    // Recursive function to delete all leaf nodes
    static Node DeleteLeafNodes(Node root) {

        // If the root is null, return null
        if (root == null) {
            return null;
        }

        // If the node itself is a leaf, 
      	// delete it
        if (root.children.Count == 0) {
            return null;
        }

        // Process children and remove 
      	// any leaf nodes
        root.children.RemoveAll(
            child => child != null && child.children.Count == 0);

        for (int i = 0; i < root.children.Count; i++) {
            root.children[i]
                = DeleteLeafNodes(root.children[i]);
        }

        return root;
    }

    // Recursive function for preorder traversal
    // of the N-ary tree
    static void preorderTraversal(Node root) {

        if (root == null) {
            return;
        }

        Console.Write(root.data + " ");
        foreach(var child in root.children) {
            preorderTraversal(child);
        }
    }

    static void Main(string[] args) {

        // Representation of given N-ary tree
        //         1
        //       / | \
        //     2   3   4
        //    /         \
        //   5           6
        Node root = new Node(1);
        root.children.Add(new Node(2));
        root.children.Add(new Node(3));
        root.children.Add(new Node(4));
        root.children[0].children.Add(new Node(5));
        root.children[2].children.Add(new Node(6));

        root = DeleteLeafNodes(root);

        preorderTraversal(root);
    }
}
JavaScript
// JavaScript Code to delete all leaf nodes
// in an N-ary tree
class Node {
    constructor(val) {
        this.data = val;
        this.children = [];
    }
}

// Recursive function to delete all leaf nodes
function deleteLeafNodes(root) {

    // If the root is null, return null
    if (!root) {
        return null;
    }

    // If the node itself is a leaf, delete it
    if (root.children.length === 0) {
        return null;
    }

    // Process children and remove any leaf nodes
    root.children = root.children.filter(child => {
        if (child && child.children.length === 0) {
            return false; // Remove this child
        }

        // Recur for non-leaf children
        child = deleteLeafNodes(child);
        return child !== null;
    });

    return root;
}

// Recursive function for preorder traversal
// of the N-ary tree
function preorderTraversal(root) {

    if (!root) {
        return;
    }

    console.log(root.data);
    for (const child of root.children) {
        preorderTraversal(child);
    }
}

// Representation of given N-ary tree
//         1
//       / | \
//     2   3   4
//    /         \
//   5           6
const root = new Node(1);
root.children.push(new Node(2));
root.children.push(new Node(3));
root.children.push(new Node(4));
root.children[0].children.push(new Node(5));
root.children[2].children.push(new Node(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.


Next Article
Article Tags :

Similar Reads