Remove all subtrees consisting only of even valued nodes from a Binary Tree

Given a Binary Tree, the task is to remove all the subtrees that do not contain any odd valued node. Print the Levelorder Traversal of the tree after removal of these subtrees.Â
Note: Print NULL for removed nodes.
Examples:Â
Input: Below is the given Tree:
         1
          \
           2
          /  \
         8   5
Output: 1 NULL 2 NULL 5
Explanation:
Tree after pruning:
         1
          \
           2
            \
            5Input: Below is the given Tree:
               1
             /   \
            2    7
           /  \   /  \
          8  10 12  5Â
Output: 1 NULL 7 NULL 5
Explanation:
Tree after pruning:
               1
               \
                7
                 \
                  5Â
Approach: To solve the given problem, the idea is to traverse the tree using DFS Traversal and a concept of backtracking will be used. Follow the below steps to solve the problem:
- Traverse the given tree using DFS Traversal and perform the following steps:
- If the root node is NULL, then return.
- If the leaf node value is even, then remove this node by returning NULL. Otherwise, return the root node from the current recursive call.
- Recursively update the left and the right subtrees using the above conditions.
- After completing the above steps, print the updated tree using the level order Traversal with NULL in place of removed nodes.
Below is the implementation of the above approach:
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;Â
// Node of the treestruct node {Â Â Â Â int data;Â Â Â Â struct node *left, *right;};Â
// Function to create a new nodenode* newNode(int key){Â Â Â Â node* temp = new node;Â Â Â Â temp->data = key;Â Â Â Â temp->left = temp->right = NULL;Â Â Â Â return (temp);}Â
// Function to print tree level wisevoid printLevelOrder(node* root){    // Base Case    if (!root)        return;Â
    // Create an empty queue for    // level order traversal    queue<node*> q;Â
    // Enqueue Root    q.push(root);Â
    while (!q.empty()) {Â
        // Print front of queue and        // remove it from queue        node* temp = q.front();        cout << temp->data << " ";        q.pop();Â
        // If left child is present        if (temp->left != NULL) {Â
            q.push(temp->left);        }Â
        // Otherwise        else if (temp->right != NULL) {Â
            cout << "NULL ";        }Â
        // If right child is present        if (temp->right != NULL) {Â
            q.push(temp->right);        }Â
        // Otherwise        else if (temp->left != NULL) {Â
            cout << "NULL ";        }    }}Â
// Function to remove subtreesnode* pruneTree(node* root){    // Base Case    if (!root) {        return NULL;    }Â
    // Search for required condition    // in left and right half    root->left = pruneTree(root->left);    root->right = pruneTree(root->right);Â
    // If the node is even    // and leaf node    if (root->data % 2 == 0        && !root->right        && !root->left)        return NULL;Â
    return root;}Â
// Driver Codeint main(){Â Â Â Â struct node* root = newNode(1);Â Â Â Â root->left = newNode(2);Â Â Â Â root->left->left = newNode(8);Â Â Â Â root->left->right = newNode(10);Â Â Â Â root->right = newNode(7);Â Â Â Â root->right->left = newNode(12);Â Â Â Â root->right->right = newNode(5);Â
    // Function Call    node* newRoot = pruneTree(root);Â
    // Print answer    printLevelOrder(newRoot);Â
    return 0;} |
Java
// Java program for the above approachimport java.util.*;class GFG{Â
// Node of the treestatic class node {Â Â Â Â int data;Â Â Â Â node left, right;};Â
// Function to create a new nodestatic node newNode(int key){Â Â Â Â node temp = new node();Â Â Â Â temp.data = key;Â Â Â Â temp.left = temp.right = null;Â Â Â Â return (temp);}Â
// Function to print tree level wisestatic void printLevelOrder(node root){       // Base Case    if (root==null)        return;Â
    // Create an empty queue for    // level order traversal    Queue<node> q = new LinkedList<>();Â
    // Enqueue Root    q.add(root);    while (!q.isEmpty())     {Â
        // Print front of queue and        // remove it from queue        node temp = q.peek();        System.out.print(temp.data+ " ");        q.remove();Â
        // If left child is present        if (temp.left != null)         {            q.add(temp.left);        }Â
        // Otherwise        else if (temp.right != null)         {            System.out.print("null ");        }Â
        // If right child is present        if (temp.right != null)         {            q.add(temp.right);        }Â
        // Otherwise        else if (temp.left != null)         {            System.out.print("null ");        }    }}Â
// Function to remove subtreesstatic node pruneTree(node root){    // Base Case    if (root == null)     {        return null;    }Â
    // Search for required condition    // in left and right half    root.left = pruneTree(root.left);    root.right = pruneTree(root.right);Â
    // If the node is even    // and leaf node    if (root.data % 2 == 0        && root.right==null        && root.left==null)        return null;Â
    return root;}Â
// Driver Codepublic static void main(String[] args){Â Â Â Â node root = newNode(1);Â Â Â Â root.left = newNode(2);Â Â Â Â root.left.left = newNode(8);Â Â Â Â root.left.right = newNode(10);Â Â Â Â root.right = newNode(7);Â Â Â Â root.right.left = newNode(12);Â Â Â Â root.right.right = newNode(5);Â
    // Function Call    node newRoot = pruneTree(root);Â
    // Print answer    printLevelOrder(newRoot);}}Â
// This code is contributed by shikhasingrajput |
Python3
# Python 3 program for the above approachÂ
# Node of the treeclass node:    def __init__(self,data):        self.data = data        self.left = None        self.right = NoneÂ
# Function to print tree level wisedef printLevelOrder(root):       # Base Case    if (root==None):        returnÂ
    # Create an empty queue for    # level order traversal    q = []Â
    # Enqueue Root    q.append(root)Â
    while(len(q)>0):        # Print front of queue and        # remove it from queue        temp = q[0]        print(temp.data,end = " ")        q = q[1:]Â
        # If left child is present        if (temp.left != None):            q.append(temp.left)Â
        # Otherwise        elif (temp.right != None):            print("NULL",end= " ")Â
        # If right child is present        if (temp.right != None):            q.append(temp.right)Â
        # Otherwise        elif (temp.left != None):            print("NULL",end = " ")Â
# Function to remove subtreesdef pruneTree(root):       # Base Case    if (root==None):        return NoneÂ
    # Search for required condition    # in left and right half    root.left = pruneTree(root.left)    root.right = pruneTree(root.right)Â
    # If the node is even    # and leaf node    if (root.data % 2 == 0 and root.right == None and root.left==None):        return NoneÂ
    return rootÂ
# Driver Codeif __name__ == '__main__':Â Â Â Â root = node(1)Â Â Â Â root.left = node(2)Â Â Â Â root.left.left = node(8)Â Â Â Â root.left.right = node(10)Â Â Â Â root.right = node(7)Â Â Â Â root.right.left = node(12)Â Â Â Â root.right.right = node(5)Â
    # Function Call    newRoot = pruneTree(root)Â
    # Print answer    printLevelOrder(newRoot)Â
    # This code is contributed by SURENDRA_GANGWAR. |
C#
// C# program for the above approachusing System;using System.Collections.Generic;Â
public class GFG{Â
// Node of the treeclass node {Â Â Â Â public int data;Â Â Â Â public node left, right;};Â
// Function to create a new nodestatic node newNode(int key){Â Â Â Â node temp = new node();Â Â Â Â temp.data = key;Â Â Â Â temp.left = temp.right = null;Â Â Â Â return (temp);}Â
// Function to print tree level wisestatic void printLevelOrder(node root){       // Base Case    if (root == null)        return;Â
    // Create an empty queue for    // level order traversal    Queue<node> q = new Queue<node>();Â
    // Enqueue Root    q.Enqueue(root);    while (q.Count != 0)     {Â
        // Print front of queue and        // remove it from queue        node temp = q.Peek();        Console.Write(temp.data+ " ");        q.Dequeue();Â
        // If left child is present        if (temp.left != null)         {            q.Enqueue(temp.left);        }Â
        // Otherwise        else if (temp.right != null)         {            Console.Write("null ");        }Â
        // If right child is present        if (temp.right != null)         {            q.Enqueue(temp.right);        }Â
        // Otherwise        else if (temp.left != null)         {            Console.Write("null ");        }    }}Â
// Function to remove subtreesstatic node pruneTree(node root){       // Base Case    if (root == null)     {        return null;    }Â
    // Search for required condition    // in left and right half    root.left = pruneTree(root.left);    root.right = pruneTree(root.right);Â
    // If the node is even    // and leaf node    if (root.data % 2 == 0        && root.right==null        && root.left==null)        return null;Â
    return root;}Â
// Driver Codepublic static void Main(String[] args){Â Â Â Â node root = newNode(1);Â Â Â Â root.left = newNode(2);Â Â Â Â root.left.left = newNode(8);Â Â Â Â root.left.right = newNode(10);Â Â Â Â root.right = newNode(7);Â Â Â Â root.right.left = newNode(12);Â Â Â Â root.right.right = newNode(5);Â
    // Function Call    node newRoot = pruneTree(root);Â
    // Print answer    printLevelOrder(newRoot);}}Â
// This code is contributed by shikhasingrajput |
Javascript
<script>    // Javascript program for the above approach         // Node of the tree    class node    {        constructor(key) {           this.left = null;           this.right = null;           this.data = key;        }    }         // Function to create a new node    function newNode(key)    {        let temp = new node(key);        return (temp);    }Â
    // Function to print tree level wise    function printLevelOrder(root)    {Â
        // Base Case        if (root == null)            return;Â
        // Create an empty queue for        // level order traversal        let q = [];Â
        // Enqueue Root        q.push(root);        while (q.length != 0)        {Â
            // Print front of queue and            // remove it from queue            let temp = q[0];            document.write(temp.data+ " ");            q.shift();Â
            // If left child is present            if (temp.left != null)            {                q.push(temp.left);            }Â
            // Otherwise            else if (temp.right != null)            {                document.write("Null ");            }Â
            // If right child is present            if (temp.right != null)            {                q.push(temp.right);            }Â
            // Otherwise            else if (temp.left != null)            {                document.write("Null ");            }        }    }         // Function to remove subtrees    function pruneTree(root)    {Â
        // Base Case        if (root == null)        {            return null;        }Â
        // Search for required condition        // in left and right half        root.left = pruneTree(root.left);        root.right = pruneTree(root.right);Â
        // If the node is even        // and leaf node        if (root.data % 2 == 0            && root.right==null            && root.left==null)            return null;Â
        return root;    }         let root = newNode(1);    root.left = newNode(2);    root.left.left = newNode(8);    root.left.right = newNode(10);    root.right = newNode(7);    root.right.left = newNode(12);    root.right.right = newNode(5);      // Function Call    let newRoot = pruneTree(root);      // Print answer    printLevelOrder(newRoot);       // This code is contributed by decode2207.</script> |
1 NULL 7 NULL 5
Â
Time Complexity: O(N)
Auxiliary Space: O(N)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



