Given a value K and a binary tree, the task is to find out number of subtrees having XOR of all its elements equal to K.
Input K = 5, Tree = 2 / \ 1 9 / \ 10 5 Output: 2 Explanation: Subtree 1: 5 It has only one element i.e. 5. So XOR of subtree = 5 Subtree 1: 2 / \ 1 9 / \ 10 5 It has elements 2, 1, 9, 10, 5. So XOR of subtree = 2 ^ 1 ^ 9 ^ 10 ^ 5 = 5 Input K = 3, Tree = 4 / \ 3 9 / \ 2 2 Output: 1 Explanation Subtree: 3 / \ 2 2 It has elements 3, 2, 2. So XOR of subtree = 3 ^ 2 ^ 2 = 3
- Traverse the tree recursively using pre-order traversal.
- For each node keep calculating the XOR of its subtree as:
XOR of its subtree = (XOR of node’s left subtree) ^ (XOR of nodes’s right subtree) ^ (node’s value)
- If the XOR of any subtree is K, increment the counter variable.
- Print the value in counter as the required count
Below is the implementation of the above approach:
Time Complexity: As in the above approach, we are iterating over each node only once, therefore it will take O(N) time where N is the number of nodes in the Binary tree.
Auxiliary Space Complexity: As in the above approach there is no extra space used, therefore the Auxiliary Space complexity will be 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.
- Count of subtrees in a Binary Tree having bitwise OR value K
- Check if a Binary Tree contains duplicate subtrees of size 2 or more
- Count of subtrees from an N-ary tree consisting of single colored nodes
- Print updated levels of each node of a Complete Binary Tree based on difference in weights of subtrees
- Count the Number of Binary Search Trees present in a Binary Tree
- Number of subtrees having odd count of even numbers
- Find Count of Single Valued Subtrees
- Count subtrees that sum up to a given value x only using single recursive function
- Count of 1's in any path in a Binary Tree
- Count even paths in Binary Tree
- Count all k-sum paths in a Binary Tree
- Count pairs in a binary tree whose sum is equal to a given value x
- Count Non-Leaf nodes in a Binary Tree
- Count of Fibonacci paths in a Binary tree
- Count of exponential paths in a Binary Tree
- Count of paths in given Binary Tree with odd bitwise AND for Q queries
- Count of nodes in a Binary Tree whose immediate children are co-prime
- Program to count leaf nodes in a binary tree
- Count nodes with two children at level L in a Binary Tree
- Count of nodes in a Binary tree with immediate children as its factors
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.