Trim given Binary Tree for any subtree containing only 0s

Given a Binary tree, the task is to trim this tree for any subtree containing only 0s.
Examples:
Input:
1
\
0
/ \
0 1
Output:
1
\
0
\
1
Explanation:
The subtree shown as bold below
does not contain any 1.
Hence it can be trimmed.
1
\
0
/ \
0 1
Input:
1
/ \
1 0
/ \ / \
1 1 0 1
/
0
Output:
1
/ \
1 0
/ \ \
1 1 1
Input:
1
/ \
0 1
/ \ / \
0 0 0 1
Output:
1
\
1
\
1
Approach: The given problem can be solved using post-order traversal. The idea is to return null node to the parent if both left and right subtree is null and value of current node is 0. This removes the subtrees which do not contain even a single 1. Follow the steps below to solve the problem:
- If the root is null, we simply return null.
- Call the function recursively on both left and right subtrees
- If left subtree and right subtree returns null and current node’s value is 0 return null
- Else return the current node itself
Below is the implementation of the above approach:
C++
// C++ program for above approachÂ
#include <iostream>using namespace std;Â
class TreeNode {Â
public:Â Â Â Â int data;Â Â Â Â TreeNode* left;Â Â Â Â TreeNode* right;Â Â Â Â TreeNode(int val)Â Â Â Â {Â Â Â Â Â Â Â Â data = val;Â Â Â Â Â Â Â Â left = NULL;Â Â Â Â Â Â Â Â right = NULL;Â Â Â Â }};Â
// Inorder function to print the treevoid inorderPrint(TreeNode* root){Â Â Â Â if (root == NULL)Â Â Â Â Â Â Â Â return;Â Â Â Â inorderPrint(root->left);Â Â Â Â cout << root->data << " ";Â Â Â Â inorderPrint(root->right);}Â
// Postorder traversalTreeNode* TrimTree(TreeNode* root){Â Â Â Â if (!root)Â Â Â Â Â Â Â Â return nullptr;Â
    // Traverse from leaf to node    root->left = TrimTree(root->left);    root->right = TrimTree(root->right);Â
    // We only trim if the node's value is 0    // and children are null    if (root->data == 0 && root->left == nullptr        && root->right == nullptr) {Â
        // We trim the subtree by returning nullptr        return nullptr;    }Â
    // Otherwise we leave the node the way it is    return root;}Â
// Driver codeint main(){Â Â Â Â /*Â Â Â Â Â Â Â Â Â Â Â 1Â Â Â Â Â Â Â Â Â /Â Â \Â Â Â Â Â Â Â 0Â Â Â Â Â 1Â Â Â Â Â Â / \Â Â Â /Â \Â Â Â Â 0Â Â Â 0Â 0Â Â Â 1Â Â Â Â */Â
    TreeNode* root = new TreeNode(1);    root->left = new TreeNode(0);    root->right = new TreeNode(1);    root->left->left = new TreeNode(0);    root->left->right = new TreeNode(0);    root->right->left = new TreeNode(0);    root->right->right = new TreeNode(1);Â
    TreeNode* ReceivedRoot = TrimTree(root);    cout << endl;    inorderPrint(ReceivedRoot);    /*              1                \                  1                    \                     1    */} |
Java
// Java program for above approachclass GFG{Â
static class TreeNode {Â
Â
    int data;    TreeNode left;    TreeNode right;    TreeNode(int val)    {        data = val;        left = null;        right = null;    }};Â
// Inorder function to print the treestatic void inorderPrint(TreeNode root){Â Â Â Â if (root == null)Â Â Â Â Â Â Â Â return;Â Â Â Â inorderPrint(root.left);Â Â Â Â System.out.print(root.data+ " ");Â Â Â Â inorderPrint(root.right);}Â
// Postorder traversalstatic TreeNode TrimTree(TreeNode root){Â Â Â Â if (root==null)Â Â Â Â Â Â Â Â return null;Â
    // Traverse from leaf to node    root.left = TrimTree(root.left);    root.right = TrimTree(root.right);Â
    // We only trim if the node's value is 0    // and children are null    if (root.data == 0 && root.left == null        && root.right == null) {Â
        // We trim the subtree by returning null        return null;    }Â
    // Otherwise we leave the node the way it is    return root;}Â
// Driver codepublic static void main(String[] args){Â Â Â Â /*Â Â Â Â Â Â Â Â Â Â Â 1Â Â Â Â Â Â Â Â Â /Â Â \Â Â Â Â Â Â Â 0Â Â Â Â Â 1Â Â Â Â Â Â / \Â Â Â /Â \Â Â Â Â 0Â Â Â 0Â 0Â Â Â 1Â Â Â Â */Â
    TreeNode root = new TreeNode(1);    root.left = new TreeNode(0);    root.right = new TreeNode(1);    root.left.left = new TreeNode(0);    root.left.right = new TreeNode(0);    root.right.left = new TreeNode(0);    root.right.right = new TreeNode(1);Â
    TreeNode ReceivedRoot = TrimTree(root);    System.out.println();    inorderPrint(ReceivedRoot);    /*              1                \                  1                    \                     1    */}}Â
// This code is contributed by shikhasingrajput |
Python3
# Python program for above approachclass TreeNode:Â
    def __init__(self, data):        self.data = data # Assign data        self.left = None        self.right = None;Â
# Inorder function to print the treedef inorderPrint(root):Â Â Â Â if (root == None):Â Â Â Â Â Â Â Â return;Â Â Â Â inorderPrint(root.left);Â Â Â Â print(root.data, end = " ");Â Â Â Â inorderPrint(root.right);Â
# Postorder traversaldef TrimTree(root):Â Â Â Â if (root == None):Â Â Â Â Â Â Â Â return None;Â
    # Traverse from leaf to Node    root.left = TrimTree(root.left);    root.right = TrimTree(root.right);Â
    # We only trim if the Node's value is 0    # and children are None    if (root.data == 0 and root.left == None and root.right == None):               # We trim the subtree by returning None        return None;Â
    # Otherwise we leave the Node the way it is    return root;Â
# Driver codeif __name__ == '__main__':Â Â Â Â '''Â Â Â Â Â Â Â Â Â Â Â 1Â Â Â Â Â Â Â Â Â /Â Â \Â Â Â Â Â Â Â 0Â Â Â Â Â 1Â Â Â Â Â Â / \Â Â Â /Â \Â Â Â Â 0Â Â Â 0Â 0Â Â Â 1Â Â Â Â Â '''Â
    root = TreeNode(1);    root.left = TreeNode(0);    root.right = TreeNode(1);    root.left.left = TreeNode(0);    root.left.right = TreeNode(0);    root.right.left = TreeNode(0);    root.right.right = TreeNode(1);Â
    ReceivedRoot = TrimTree(root);    print();    inorderPrint(ReceivedRoot);    '''              1                \                  1                    \                     1     '''Â
# This code is contributed by shikhasingrajput |
C#
// C# program for above approachusing System;public class GFG{Â
class TreeNode {Â
    public int data;    public TreeNode left;    public TreeNode right;    public TreeNode(int val)    {        data = val;        left = null;        right = null;    }};Â
// Inorder function to print the treestatic void inorderPrint(TreeNode root){Â Â Â Â if (root == null)Â Â Â Â Â Â Â Â return;Â Â Â Â inorderPrint(root.left);Â Â Â Â Console.Write(root.data+ " ");Â Â Â Â inorderPrint(root.right);}Â
// Postorder traversalstatic TreeNode TrimTree(TreeNode root){Â Â Â Â if (root==null)Â Â Â Â Â Â Â Â return null;Â
    // Traverse from leaf to node    root.left = TrimTree(root.left);    root.right = TrimTree(root.right);Â
    // We only trim if the node's value is 0    // and children are null    if (root.data == 0 && root.left == null        && root.right == null) {Â
        // We trim the subtree by returning null        return null;    }Â
    // Otherwise we leave the node the way it is    return root;}Â
// Driver codepublic static void Main(String[] args){Â Â Â Â /*Â Â Â Â Â Â Â Â Â Â Â 1Â Â Â Â Â Â Â Â Â /Â Â \Â Â Â Â Â Â Â 0Â Â Â Â Â 1Â Â Â Â Â Â / \Â Â Â /Â \Â Â Â Â 0Â Â Â 0Â 0Â Â Â 1Â Â Â Â */Â
    TreeNode root = new TreeNode(1);    root.left = new TreeNode(0);    root.right = new TreeNode(1);    root.left.left = new TreeNode(0);    root.left.right = new TreeNode(0);    root.right.left = new TreeNode(0);    root.right.right = new TreeNode(1);Â
    TreeNode ReceivedRoot = TrimTree(root);    Console.WriteLine();    inorderPrint(ReceivedRoot);    /*              1                \                  1                    \                     1    */}}Â
// This code is contributed by shikhasingrajput |
Javascript
<script>// JavaScript Program to implement// the above approachÂ
class TreeNode {Â
    constructor( val)    {        this.data = val;        this.left = null;        this.right = null;    }};Â
// Inorder function to print the treefunction inorderPrint( root){Â Â Â Â if (root == null)Â Â Â Â Â Â Â Â return;Â Â Â Â inorderPrint(root.left);Â Â Â Â document.write(root.data + " ");Â Â Â Â inorderPrint(root.right);}Â
// Postorder traversalfunction TrimTree( root){Â Â Â Â if (!root)Â Â Â Â Â Â Â Â return null;Â
    // Traverse from leaf to node    root.left = TrimTree(root.left);    root.right = TrimTree(root.right);Â
    // We only trim if the node's value is 0    // and children are null    if (root.data == 0 && root.left == null        && root.right == null) {Â
        // We trim the subtree by returning nullptr        return null;    }Â
    // Otherwise we leave the node the way it is    return root;}Â
// Driver codeÂ
    /*           1         /  \       0     1      / \   / \    0   0 0   1    */Â
    let root = new TreeNode(1);    root.left = new TreeNode(0);    root.right = new TreeNode(1);    root.left.left = new TreeNode(0);    root.left.right = new TreeNode(0);    root.right.left = new TreeNode(0);    root.right.right = new TreeNode(1);Â
    let ReceivedRoot = TrimTree(root);    document.write('<br>')    inorderPrint(ReceivedRoot);    /*              1                \                  1                    \                     1    */Â
// This code is contributed by Potta LokeshÂ
    </script> |
Output:Â
1 1 1
Â
Time Complexity: O(N), where N is the number of nodes in the tree.
Auxiliary Space: O(H), the recursion call stack can be as large as the height H of the tree. In the worst-case scenario, H = N, when the tree is skewed.
Â
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!



