Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Tree
  • Practice Tree
  • MCQs on Tree
  • Tutorial on Tree
  • Types of Trees
  • Basic operations
  • Tree Traversal
  • Binary Tree
  • Complete Binary Tree
  • Ternary Tree
  • Binary Search Tree
  • Red-Black Tree
  • AVL Tree
  • Full Binary Tree
  • B-Tree
  • Advantages & Disadvantages
Open In App
Next Article:
Count of substrings that start and end with 1 in given Binary String
Next article icon

Check if the given Binary Tree have a Subtree with equal no of 1’s and 0’s

Last Updated : 03 Jun, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a Binary Tree having data at nodes as either 0’s or 1’s. The task is to find out whether there exists a subtree having an equal number of 1’s and 0’s.

Examples: 

Input : 
 

Output : True 
There are two subtrees present in the above tree where the number of 1’s is equal to the number of 0’s.

Input : 
 

Output : False 
There is no such subtree present which has the number of 1’s equal to number of 0’s

 

Approach: The idea is to change the data 0’s of the tree to -1. So that it becomes very easy to find the subtree having equal number of 0’s and 1’s. After converting all 0’s to -1, create a sum tree. After creating the sum tree, each node will contain the sum of all node lying under it. 

Traverse the tree again and find if there is a node having 0 sum, it means that there is a subtree that has the equal number of 1’s and -1’s, i.e. equal number of 1’s and 0’s.

Below is the implementation of the above approach: 

C++




// C++ program to check if there exist a
// subtree with equal number of 1's and 0's
 
#include <bits/stdc++.h>
using namespace std;
 
// Binary Tree Node
struct node {
    int data;
    struct node *right, *left;
};
 
// Utility function to create a new node
struct node* newnode(int key)
{
    struct node* temp = new node;
    temp->data = key;
    temp->right = NULL;
    temp->left = NULL;
 
    return temp;
}
 
// Function to convert all 0's in the
// tree to -1
void convert(struct node* root)
{
    if (root == NULL) {
        return;
    }
 
    // Move to right subtree
    convert(root->right);
 
    // Replace the 0's with -1 in the tree
    if (root->data == 0) {
        root->data = -1;
    }
 
    // Move to left subtree
    convert(root->left);
}
 
// Function to convert the tree to a SUM tree
int sum_tree(struct node* root)
{
    int a = 0, b = 0;
 
    if (root == NULL) {
        return 0;
    }
 
    a = sum_tree(root->left);
    b = sum_tree(root->right);
 
    root->data = root->data + a + b;
 
    return root->data;
}
 
// Function to check if there exists a subtree
// with equal no of 1s and 0s
int checkSubtree(struct node* root, int d)
{
    if (root == NULL) {
        return 0;
    }
 
    // Check if there is a subtree with equal
    // 1s and 0s or not
    if (d == 0) {
        d = checkSubtree(root->left, d);
    }
 
    if (root->data == 0) {
        d = 1;
        return d;
    }
 
    if (d == 0) {
        d = checkSubtree(root->right, d);
    }
 
    return d;
}
 
// Driver Code
int main()
{
    // Create the Binary Tree
    struct node* root = newnode(1);
    root->right = newnode(0);
    root->right->right = newnode(1);
    root->right->right->right = newnode(1);
    root->left = newnode(0);
    root->left->left = newnode(1);
    root->left->left->left = newnode(1);
    root->left->right = newnode(0);
    root->left->right->left = newnode(1);
    root->left->right->left->left = newnode(1);
    root->left->right->right = newnode(0);
    root->left->right->right->left = newnode(0);
    root->left->right->right->left->left = newnode(1);
 
    // Convert all 0s in tree to -1
    convert(root);
 
    // Convert the tree into a SUM tree
    sum_tree(root);
 
    // Check if required Subtree exists
    int d = 0;
    if (checkSubtree(root, d)) {
        cout << "True" << endl;
    }
    else {
        cout << "False" << endl;
    }
 
    return 0;
}
 
 

Java




// Java program to check if there exist a
// subtree with equal number of 1's and 0's
 
import java.util.*;
class GFG{
 
    // Binary Tree Node
    static class node {
        int data;
        node right, left;
    };
     
    // Utility function to create a new node
    static node newnode(int key)
    {
        node temp = new node();
        temp.data = key;
        temp.right = null;
        temp.left = null;
     
        return temp;
    }
     
    // Function to convert all 0's in the
    // tree to -1
    static void convert(node root)
    {
        if (root == null) {
            return;
        }
     
        // Move to right subtree
        convert(root.right);
     
        // Replace the 0's with -1 in the tree
        if (root.data == 0) {
            root.data = -1;
        }
     
        // Move to left subtree
        convert(root.left);
    }
     
    // Function to convert the tree to a SUM tree
    static int sum_tree(node root)
    {
        int a = 0, b = 0;
     
        if (root == null) {
            return 0;
        }
     
        a = sum_tree(root.left);
        b = sum_tree(root.right);
     
        root.data = root.data + a + b;
     
        return root.data;
    }
     
    // Function to check if there exists a subtree
    // with equal no of 1s and 0s
    static int checkSubtree(node root, int d)
    {
        if (root == null) {
            return 0;
        }
     
        // Check if there is a subtree with equal
        // 1s and 0s or not
        if (d == 0) {
            d = checkSubtree(root.left, d);
        }
     
        if (root.data == 0) {
            d = 1;
            return d;
        }
     
        if (d == 0) {
            d = checkSubtree(root.right, d);
        }
     
        return d;
    }
     
    // Driver Code
    public static void main(String args[])
    {
        // Create the Binary Tree
        node root = newnode(1);
        root.right = newnode(0);
        root.right.right = newnode(1);
        root.right.right.right = newnode(1);
        root.left = newnode(0);
        root.left.left = newnode(1);
        root.left.left.left = newnode(1);
        root.left.right = newnode(0);
        root.left.right.left = newnode(1);
        root.left.right.left.left = newnode(1);
        root.left.right.right = newnode(0);
        root.left.right.right.left = newnode(0);
        root.left.right.right.left.left = newnode(1);
     
        // Convert all 0s in tree to -1
        convert(root);
     
        // Convert the tree into a SUM tree
        sum_tree(root);
     
        // Check if required Subtree exists
        int d = 0;
        if (checkSubtree(root, d)>=1) {
            System.out.println("True");
        }
        else {
            System.out.println("False");
        }
    }
}
 
 
// This code is contributed by AbhiThakur
 
 

Python3




# Python3 program to check if there exist a
# subtree with equal number of 1's and 0's
 
# Binary Tree Node
class node:
     
    def __init__(self, key):
         
        self.data = key
        self.left = None
        self.right = None
 
# Function to convert all 0's in the
# tree to -1
def convert(root):
 
    if (root == None):
        return
 
    # Move to right subtree
    convert(root.right)
 
    # Replace the 0's with -1
    # in the tree
    if (root.data == 0):
        root.data = -1
 
    # Move to left subtree
    convert(root.left)
 
# Function to convert the tree
# to a SUM tree
def sum_tree(root):
     
    a = 0
    b = 0
 
    if (root == None):
        return 0
 
    a = sum_tree(root.left)
    b = sum_tree(root.right)
 
    root.data = root.data + a + b
 
    return root.data
 
# Function to check if there exists
# a subtree with equal no of 1s and 0s
def checkSubtree(root, d):
     
    if (root == None):
        return 0
 
    # Check if there is a subtree with
    # equal 1s and 0s or not
    if (d == 0):
        d = checkSubtree(root.left, d)
 
    if (root.data == 0):
        d = 1
        return d
 
    if (d == 0):
        d = checkSubtree(root.right, d)
 
    return d
 
# Driver Code
if __name__ == '__main__':
     
    # Create the Binary Tree
    root = node(1)
    root.right = node(0)
    root.right.right = node(1)
    root.right.right.right = node(1)
    root.left = node(0)
    root.left.left = node(1)
    root.left.left.left = node(1)
    root.left.right = node(0)
    root.left.right.left = node(1)
    root.left.right.left.left = node(1)
    root.left.right.right = node(0)
    root.left.right.right.left = node(0)
    root.left.right.right.left.left = node(1)
 
    # Convert all 0s in tree to -1
    convert(root)
 
    # Convert the tree into a SUM tree
    sum_tree(root)
 
    # Check if required Subtree exists
    d = 0
     
    if (checkSubtree(root, d)):
        print("True")
    else:
        print("False")
 
# This code is contributed by mohit kumar 29
 
 

C#




// C# program to check if there exist a
// subtree with equal number of 1's and 0's
using System;
 
class GFG{
  
    // Binary Tree Node
    class node {
        public int data;
        public node right, left;
    };
      
    // Utility function to create a new node
    static node newnode(int key)
    {
        node temp = new node();
        temp.data = key;
        temp.right = null;
        temp.left = null;
      
        return temp;
    }
      
    // Function to convert all 0's in the
    // tree to -1
    static void convert(node root)
    {
        if (root == null) {
            return;
        }
      
        // Move to right subtree
        convert(root.right);
      
        // Replace the 0's with -1 in the tree
        if (root.data == 0) {
            root.data = -1;
        }
      
        // Move to left subtree
        convert(root.left);
    }
      
    // Function to convert the tree to a SUM tree
    static int sum_tree(node root)
    {
        int a = 0, b = 0;
      
        if (root == null) {
            return 0;
        }
      
        a = sum_tree(root.left);
        b = sum_tree(root.right);
      
        root.data = root.data + a + b;
      
        return root.data;
    }
      
    // Function to check if there exists a subtree
    // with equal no of 1s and 0s
    static int checkSubtree(node root, int d)
    {
        if (root == null) {
            return 0;
        }
      
        // Check if there is a subtree with equal
        // 1s and 0s or not
        if (d == 0) {
            d = checkSubtree(root.left, d);
        }
      
        if (root.data == 0) {
            d = 1;
            return d;
        }
      
        if (d == 0) {
            d = checkSubtree(root.right, d);
        }
      
        return d;
    }
      
    // Driver Code
    public static void Main(String []args)
    {
        // Create the Binary Tree
        node root = newnode(1);
        root.right = newnode(0);
        root.right.right = newnode(1);
        root.right.right.right = newnode(1);
        root.left = newnode(0);
        root.left.left = newnode(1);
        root.left.left.left = newnode(1);
        root.left.right = newnode(0);
        root.left.right.left = newnode(1);
        root.left.right.left.left = newnode(1);
        root.left.right.right = newnode(0);
        root.left.right.right.left = newnode(0);
        root.left.right.right.left.left = newnode(1);
      
        // Convert all 0s in tree to -1
        convert(root);
      
        // Convert the tree into a SUM tree
        sum_tree(root);
      
        // Check if required Subtree exists
        int d = 0;
        if (checkSubtree(root, d) >= 1) {
            Console.WriteLine("True");
        }
        else {
            Console.WriteLine("False");
        }
    }
}
 
// This code is contributed by sapnasingh4991
 
 

Javascript




<script>
 
// Javascript program to check if there exist a
// subtree with equal number of 1's and 0's
class Node
{
    constructor(key)
    {
        this.data = key;
        this.left = null;
        this.right = null;
    }
}
     
// Function to convert all 0's in the
// tree to -1
function convert(root)
{
    if (root == null)
    {
        return;
    }
  
    // Move to right subtree
    convert(root.right);
  
    // Replace the 0's with -1 in the tree
    if (root.data == 0)
    {
        root.data = -1;
    }
  
    // Move to left subtree
    convert(root.left);
}
 
// Function to convert the tree to a SUM tree
function sum_tree(root)
{
    let a = 0, b = 0;
  
    if (root == null)
    {
        return 0;
    }
  
    a = sum_tree(root.left);
    b = sum_tree(root.right);
  
    root.data = root.data + a + b;
  
    return root.data;
}
 
// Function to check if there exists a subtree
// with equal no of 1s and 0s
function checkSubtree(root, d)
{
    if (root == null)
    {
        return 0;
    }
  
    // Check if there is a subtree with equal
    // 1s and 0s or not
    if (d == 0)
    {
        d = checkSubtree(root.left, d);
    }
  
    if (root.data == 0)
    {
        d = 1;
        return d;
    }
  
    if (d == 0)
    {
        d = checkSubtree(root.right, d);
    }
    return d;
}
 
// Driver Code
 
// Create the Binary Tree
let root = new Node(1);
root.right = new Node(0);
root.right.right = new Node(1);
root.right.right.right = new Node(1);
root.left = new Node(0);
root.left.left = new Node(1);
root.left.left.left = new Node(1);
root.left.right = new Node(0);
root.left.right.left = new Node(1);
root.left.right.left.left = new Node(1);
root.left.right.right = new Node(0);
root.left.right.right.left = new Node(0);
root.left.right.right.left.left = new Node(1);
 
// Convert all 0s in tree to -1
convert(root);
 
// Convert the tree into a SUM tree
sum_tree(root);
 
// Check if required Subtree exists
let d = 0;
if (checkSubtree(root, d) >= 1)
{
    document.write("True<br>");
}
else
{
    document.write("False<br>");
}
 
// This code is contributed by unknown2108
 
</script>
 
 
Output: 
True

 

Time Complexity: O(N) 
Space Complexity: O(1)
 



Next Article
Count of substrings that start and end with 1 in given Binary String

V

vabzcode12
Improve
Article Tags :
  • Data Structures
  • DSA
  • Tree
  • Binary Tree
Practice Tags :
  • Data Structures
  • Tree

Similar Reads

  • Check if the given binary tree has a sub-tree with equal no of 1's and 0's | Set 2
    Given a tree having every node's value as either 0 or 1, the task is to find whether the given binary tree contains any sub-tree that has equal number of 0's and 1's, if such sub-tree is found then print Yes else print No.Examples: Input: Output: Yes There are two sub-trees with equal number of 1's
    10 min read
  • Check if a Binary Tree is an Even-Odd Tree or not
    Given a Binary Tree, the task is to check if the binary tree is an Even-Odd binary tree or not. A Binary Tree is called an Even-Odd Tree when all the nodes which are at even levels have even values (assuming root to be at level 0) and all the nodes which are at odd levels have odd values. Examples:
    15+ min read
  • Check whether a given binary tree is skewed binary tree or not?
    Given a Binary Tree check whether it is skewed binary tree or not. A skewed tree is a tree where each node has only one child node or none. Examples: Input : 5 / 4 \ 3 / 2 Output : Yes Input : 5 / 4 \ 3 / \ 2 4 Output : No The idea is to check if a node has two children. If node has two children ret
    13 min read
  • Count of substrings that start and end with 1 in given Binary String
    Given a binary string, count the number of substrings that start and end with 1. Examples: Input: "00100101"Output: 3Explanation: three substrings are "1001", "100101" and "101" Input: "1001"Output: 1Explanation: one substring "1001" Recommended PracticeCount SubstringsTry It!Count of substrings tha
    12 min read
  • Check if the given n-ary tree is a binary tree
    Given an n-ary tree consisting of n nodes, the task is to check whether the given tree is binary or not.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 multip
    6 min read
  • Check if a Binary Tree is subtree of another binary tree | Set 1
    Given two binary trees, check if the first tree is a subtree of the second one. A subtree of a tree T(root1) is a tree S(root2) consisting of a node in T and all of its descendants in T. The subtree corresponding to the root node is the entire tree and the subtree corresponding to any other node is
    9 min read
  • Check if a Binary Tree contains duplicate subtrees of size 2 or more
    Given a Binary Tree, the task is to check whether the Binary tree contains a duplicate sub-tree of size 2 or more. Note: Two same leaf nodes are not considered as the subtree as the size of a leaf node is one. Example: Input: Output: TrueExplanation: Table of Content [Naive Approach] Generating All
    15 min read
  • Check if a given Binary Tree is Sum Tree
    Given a binary tree, the task is to check if it is a Sum Tree. A Sum Tree is a Binary Tree where the value of a node is equal to the sum of the nodes present in its left subtree and right subtree. An empty tree is Sum Tree and the sum of an empty tree can be considered as 0. A leaf node is also cons
    15+ min read
  • Count of nodes with average of left subtree at least K in a given Binary Tree
    Given a binary tree and a number K, the task is to count the number of nodes having the average of the values in their left subtree greater than or equal to K. Examples: Input : K=5Tree: 2 / \ 5 4 / \ / \ 5 6 6 2 \ / 5 4Output: 3Explanation: 2 -------- level 0 / \ 5 4 -------- level 1 / \ / \ 5 6 6
    15+ min read
  • Generate Binary String with equal number of 01 and 10 Subsequence
    Given an integer N (N > 2), the task is to generate a binary string of size N that consists of equal numbers of "10" & "01" subsequences and also the string should contain at least one '0' and one '1' Note: If multiple such strings exist, print any. Examples: Input: 4Output: 0110Explanation :
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences