Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Trim given Binary Tree for any subtree containing only 0s

  • Difficulty Level : Medium
  • Last Updated : 30 Sep, 2021

Given a Binary tree, the task is to trim this tree for any subtree containing only 0s.

Examples:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

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 tree
void inorderPrint(TreeNode* root)
{
    if (root == NULL)
        return;
    inorderPrint(root->left);
    cout << root->data << " ";
    inorderPrint(root->right);
}
 
// Postorder traversal
TreeNode* 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 code
int 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 approach
class GFG{
 
static class TreeNode {
 
 
    int data;
    TreeNode left;
    TreeNode right;
    TreeNode(int val)
    {
        data = val;
        left = null;
        right = null;
    }
};
 
// Inorder function to print the tree
static void inorderPrint(TreeNode root)
{
    if (root == null)
        return;
    inorderPrint(root.left);
    System.out.print(root.data+ " ");
    inorderPrint(root.right);
}
 
// Postorder traversal
static 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 code
public 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

C#




// C# program for above approach
using 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 tree
static void inorderPrint(TreeNode root)
{
    if (root == null)
        return;
    inorderPrint(root.left);
    Console.Write(root.data+ " ");
    inorderPrint(root.right);
}
 
// Postorder traversal
static 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 code
public 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 tree
function inorderPrint( root)
{
    if (root == null)
        return;
    inorderPrint(root.left);
    document.write(root.data + " ");
    inorderPrint(root.right);
}
 
// Postorder traversal
function 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.

 




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!