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.
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.
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:
Time Complexity: O(N)
Space Complexity: O(1)
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.
- Check if a binary tree is subtree of another binary tree | Set 1
- Check if a binary tree is subtree of another binary tree | Set 2
- Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
- Find the largest BST subtree in a given Binary Tree | Set 1
- Subtree with given sum in a Binary Tree
- Find the largest Complete Subtree in a given Binary Tree
- Find the largest Perfect Subtree in a given Binary Tree
- Change a Binary Tree so that every node stores sum of all nodes in left subtree
- Convert a Binary Tree such that every node stores the sum of all nodes in its right subtree
- Duplicate subtree in Binary Tree | SET 2
- Check if the given binary tree has a sub-tree with equal no of 1's and 0's | Set 2
- Find the Kth node in the DFS traversal of a given subtree in a Tree
- Count of distinct colors in a subtree of a Colored Tree with given min frequency for Q queries
- Find GCD of each subtree of a given node in an N-ary Tree for Q queries
- Even size subtree in n-ary tree
- Subtree of all nodes in a tree using DFS
- Euler Tour | Subtree Sum using Segment Tree
- Find largest subtree sum in a tree
- Number of leaf nodes in the subtree of every node of an n-ary tree
- Queries for DFS of a subtree in a tree
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.