Print the Forests of a Binary Tree after removal of given Nodes

Given a Binary Tree and an array arr[] consisting of values of nodes to be deleted, the task is to print Inorder Traversal of the forests after deleting the nodes.
Examples:
Input: arr[] = {10, 5}Â
Â10 / \ 20 30 / \ \ 4 5 7Output:Â
4 20Â
30 7
Input: arr[] = {5}Â
Â1 / \ 5 6 / \ 10 12Output:Â
10Â
1 6 12
Approach: Follow the below steps to solve the problem:
- Perform the Postorder Traversal of the Binary Tree.
- For each node, check if it contains the value to be deleted.
- If found to be true, store its child as the root of the forest. Print the forest by Inorder Traversal.
Below is the implementation of the above approach:
C++
// C++ Program to implement// the above approach#include <bits/stdc++.h>using namespace std;Â
// Stores the nodes to be deletedunordered_map<int, bool> mp;Â
// Structure of a Tree nodestruct Node {Â Â Â Â int key;Â Â Â Â struct Node *left, *right;};Â
// Function to create a new nodeNode* newNode(int key){Â Â Â Â Node* temp = new Node;Â Â Â Â temp->key = key;Â Â Â Â temp->left = temp->right = NULL;Â Â Â Â return (temp);}Â
// Function to check whether the node// needs to be deleted or notbool deleteNode(int nodeVal){Â Â Â Â return mp.find(nodeVal) != mp.end();}Â
// Function to perform tree pruning// by performing post order traversalNode* treePruning(Node* root, vector<Node*>& result){Â Â Â Â if (root == NULL)Â Â Â Â Â Â Â Â return NULL;Â
    root->left = treePruning(root->left, result);    root->right = treePruning(root->right, result);Â
    // If the node needs to be deleted    if (deleteNode(root->key)) {Â
        // Store the its subtree        if (root->left) {            result.push_back(root->left);        }        if (root->right) {            result.push_back(root->right);        }        return NULL;    }Â
    return root;}Â
// Perform Inorder Traversalvoid printInorderTree(Node* root){Â Â Â Â if (root == NULL)Â Â Â Â Â Â Â Â return;Â
    printInorderTree(root->left);    cout << root->key << " ";    printInorderTree(root->right);}Â
// Function to print the forestsvoid printForests(Node* root, int arr[], int n){Â Â Â Â for (int i = 0; i < n; i++) {Â Â Â Â Â Â Â Â mp[arr[i]] = true;Â Â Â Â }Â
    // Stores the remaining nodes    vector<Node*> result;Â
    if (treePruning(root, result))        result.push_back(root);Â
    // Print the inorder traversal of Forests    for (int i = 0; i < result.size(); i++) {        printInorderTree(result[i]);        cout << endl;    }}Â
// Driver Codeint main(){Â
    Node* root = newNode(1);    root->left = newNode(12);    root->right = newNode(13);    root->right->left = newNode(14);    root->right->right = newNode(15);    root->right->left->left = newNode(21);    root->right->left->right = newNode(22);    root->right->right->left = newNode(23);    root->right->right->right = newNode(24);Â
    int arr[] = { 14, 23, 1 };    int n = sizeof(arr) / sizeof(arr[0]);    printForests(root, arr, n);} |
Java
// Java Program to implement// the above approachimport java.util.*;class GFG{Â
// Stores the nodes to be deletedstatic HashMap<Integer,                  Boolean> mp = new HashMap<>();Â
// Structure of a Tree nodestatic class Node{Â Â Â Â int key;Â Â Â Â Node left, right;};Â
// Function to create a new nodestatic Node newNode(int key){Â Â Â Â Node temp = new Node();Â Â Â Â temp.key = key;Â Â Â Â temp.left = temp.right = null;Â Â Â Â return (temp);}Â
// Function to check whether the node// needs to be deleted or notstatic boolean deleteNode(int nodeVal){Â Â Â Â return mp.containsKey(nodeVal);}Â
// Function to perform tree pruning// by performing post order traversalstatic Node treePruning(Node root, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Vector<Node> result){Â Â Â Â if (root == null)Â Â Â Â Â Â Â Â return null;Â
    root.left = treePruning(root.left, result);    root.right = treePruning(root.right, result);Â
    // If the node needs to be deleted    if (deleteNode(root.key))     {Â
        // Store the its subtree        if (root.left != null)         {            result.add(root.left);        }        if (root.right != null)        {            result.add(root.right);        }        return null;    }    return root;}Â
// Perform Inorder Traversalstatic void printInorderTree(Node root){Â Â Â Â if (root == null)Â Â Â Â Â Â Â Â return;Â
    printInorderTree(root.left);    System.out.print(root.key + " ");    printInorderTree(root.right);}Â
// Function to print the forestsstatic void printForests(Node root, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â int arr[], int n){Â Â Â Â for (int i = 0; i < n; i++)Â Â Â Â {Â Â Â Â Â Â Â Â mp.put(arr[i], true);Â Â Â Â }Â
    // Stores the remaining nodes    Vector<Node> result = new Vector<>();Â
    if (treePruning(root, result) != null)        result.add(root);Â
    // Print the inorder traversal of Forests    for (int i = 0; i < result.size(); i++)     {        printInorderTree(result.get(i));        System.out.println();    }}Â
// Driver Codepublic static void main(String[] args){Â
    Node root = newNode(1);    root.left = newNode(12);    root.right = newNode(13);    root.right.left = newNode(14);    root.right.right = newNode(15);    root.right.left.left = newNode(21);    root.right.left.right = newNode(22);    root.right.right.left = newNode(23);    root.right.right.right = newNode(24);Â
    int arr[] = { 14, 23, 1 };    int n = arr.length;    printForests(root, arr, n);}}Â
// This code is contributed by Rajput-Ji |
Python3
# Python3 Program to implement# the above approach  # Stores the nodes to be deletedmp = dict()  # Structure of a Tree nodeclass Node:         def __init__(self, key):                 self.key = key        self.left = None        self.right = None     # Function to create a new nodedef newNode(key):Â
    temp = Node(key)    return temp  # Function to check whether the node# needs to be deleted or notdef deleteNode(nodeVal):Â
    if nodeVal in mp:        return True    else:        return FalseÂ
# Function to perform tree pruning# by performing post order traversaldef treePruning( root, result):Â
    if (root == None):        return None;      root.left = treePruning(root.left, result);    root.right = treePruning(root.right, result);      # If the node needs to be deleted    if (deleteNode(root.key)):          # Store the its subtree        if (root.left):            result.append(root.left);                 if (root.right):            result.append(root.right);                 return None;         return root;Â
# Perform Inorder Traversaldef printInorderTree(root):Â
    if (root == None):        return;      printInorderTree(root.left);    print(root.key, end=' ')    printInorderTree(root.right);  # Function to print the forestsdef printForests(root, arr, n):    for i in range(n):           mp[arr[i]] = True;         # Stores the remaining nodes    result = []      if (treePruning(root, result)):        result.append(root);      # Print the inorder traversal of Forests    for i in range(len(result)):             printInorderTree(result[i]);        print()         # Driver Codeif __name__=='__main__':      root = newNode(1);    root.left = newNode(12);    root.right = newNode(13);    root.right.left = newNode(14);    root.right.right = newNode(15);    root.right.left.left = newNode(21);    root.right.left.right = newNode(22);    root.right.right.left = newNode(23);    root.right.right.right = newNode(24);      arr = [ 14, 23, 1 ]    n = len(arr)    printForests(root, arr, n);Â
# This code is contributed by rutvik_56 |
C#
// C# program to implement// the above approachusing System;using System.Collections.Generic;Â
class GFG{Â
// Stores the nodes to be deletedstatic Dictionary<int,                   Boolean> mp = new Dictionary<int,                                               Boolean>();Â
// Structure of a Tree nodeclass Node{Â Â Â Â public int key;Â Â Â Â public Node left, right;};Â
// Function to create a new nodestatic Node newNode(int key){Â Â Â Â Node temp = new Node();Â Â Â Â temp.key = key;Â Â Â Â temp.left = temp.right = null;Â Â Â Â return (temp);}Â
// Function to check whether the node// needs to be deleted or notstatic bool deleteNode(int nodeVal){Â Â Â Â return mp.ContainsKey(nodeVal);}Â
// Function to perform tree pruning// by performing post order traversalstatic Node treePruning(Node root, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â List<Node> result){Â Â Â Â if (root == null)Â Â Â Â Â Â Â Â return null;Â
    root.left = treePruning(root.left, result);    root.right = treePruning(root.right, result);Â
    // If the node needs to be deleted    if (deleteNode(root.key))     {Â
        // Store the its subtree        if (root.left != null)         {            result.Add(root.left);        }        if (root.right != null)        {            result.Add(root.right);        }        return null;    }    return root;}Â
// Perform Inorder Traversalstatic void printInorderTree(Node root){Â Â Â Â if (root == null)Â Â Â Â Â Â Â Â return;Â
    printInorderTree(root.left);    Console.Write(root.key + " ");    printInorderTree(root.right);}Â
// Function to print the forestsstatic void printForests(Node root, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â int []arr, int n){Â Â Â Â for(int i = 0; i < n; i++)Â Â Â Â {Â Â Â Â Â Â Â Â mp.Add(arr[i], true);Â Â Â Â }Â
    // Stores the remaining nodes    List<Node> result = new List<Node>();Â
    if (treePruning(root, result) != null)        result.Add(root);Â
    // Print the inorder traversal of Forests    for(int i = 0; i < result.Count; i++)     {        printInorderTree(result[i]);        Console.WriteLine();    }}Â
// Driver Codepublic static void Main(String[] args){Â Â Â Â Node root = newNode(1);Â Â Â Â root.left = newNode(12);Â Â Â Â root.right = newNode(13);Â Â Â Â root.right.left = newNode(14);Â Â Â Â root.right.right = newNode(15);Â Â Â Â root.right.left.left = newNode(21);Â Â Â Â root.right.left.right = newNode(22);Â Â Â Â root.right.right.left = newNode(23);Â Â Â Â root.right.right.right = newNode(24);Â
    int []arr = { 14, 23, 1 };    int n = arr.Length;    printForests(root, arr, n);}}Â
// This code is contributed by Amit Katiyar |
Javascript
<script>    // Javascript Program to implement the above approach         // Stores the nodes to be deleted    let mp = new Map();Â
    // Structure of a Tree node    class Node    {        constructor(key) {           this.left = this.right = null;           this.key = key;        }    }         // Function to create a new node    function newNode(key)    {        let temp = new Node(key);        return (temp);    }Â
    // Function to check whether the node    // needs to be deleted or not    function deleteNode(nodeVal)    {        return mp.has(nodeVal);    }Â
    // Function to perform tree pruning    // by performing post order traversal    function treePruning(root, result)    {        if (root == null)            return null;Â
        root.left = treePruning(root.left, result);        root.right = treePruning(root.right, result);Â
        // If the node needs to be deleted        if (deleteNode(root.key))        {Â
            // Store the its subtree            if (root.left != null)            {                result.push(root.left);            }            if (root.right != null)            {                result.push(root.right);            }            return null;        }        return root;    }Â
    // Perform Inorder Traversal    function printInorderTree(root)    {        if (root == null)            return;Â
        printInorderTree(root.left);        document.write(root.key + " ");        printInorderTree(root.right);    }Â
    // Function to print the forests    function printForests(root, arr, n)    {        for (let i = 0; i < n; i++)        {            mp.set(arr[i], true);        }Â
        // Stores the remaining nodes        let result = [];Â
        if (treePruning(root, result) != null)            result.push(root);Â
        // Print the inorder traversal of Forests        for (let i = 0; i < result.length; i++)        {            printInorderTree(result[i]);            document.write("</br>");        }    }         let root = newNode(1);    root.left = newNode(12);    root.right = newNode(13);    root.right.left = newNode(14);    root.right.right = newNode(15);    root.right.left.left = newNode(21);    root.right.left.right = newNode(22);    root.right.right.left = newNode(23);    root.right.right.right = newNode(24);      let arr = [ 14, 23, 1 ];    let n = arr.length;    printForests(root, arr, n);Â
</script> |
Output:Â
21 22 12 13 15 24
Â
Time Complexity: O(N)
Auxiliary Space: O(N)
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



