Count of subtrees in a Binary Tree having XOR value K
Last Updated :
29 Nov, 2023
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.
Examples:
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
Approach :
- 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:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node *left, *right;
};
struct Node* newNode( int data)
{
struct Node* newNode = new Node;
newNode->data = data;
newNode->left
= newNode->right = NULL;
return (newNode);
}
int rec(Node* root, int & res, int & k)
{
if (root == NULL) {
return 0;
}
int xr = root->data;
xr ^= rec(root->left, res, k);
xr ^= rec(root->right, res, k);
if (xr == k) {
res++;
}
return xr;
}
int findCount(Node* root, int K)
{
int res = 0;
rec(root, res, K);
return res;
}
int main( void )
{
struct Node* root = newNode(2);
root->left = newNode(1);
root->right = newNode(9);
root->left->left = newNode(10);
root->left->right = newNode(5);
int K = 5;
cout << findCount(root, K);
return 0;
}
|
Java
import java.util.*;
class GFG{
static class Node
{
int data;
Node left,right;
};
static int res;
static int k;
static Node newNode( int data)
{
Node newNode = new Node();
newNode.data = data;
newNode.left= null ;
newNode.right = null ;
return newNode;
}
static int rec(Node root)
{
if (root == null ) {
return 0 ;
}
int xr = (root.data);
xr ^= rec(root.left);
xr ^= rec(root.right);
if (xr == k) {
res++;
}
return xr;
}
static int findCount(Node root, int K)
{
res = 0 ;
k = K;
rec(root);
return res;
}
public static void main(String args[])
{
Node root = newNode( 2 );
root.left = newNode( 1 );
root.right = newNode( 9 );
root.left.left =newNode( 10 );
root.left.right = newNode( 5 );
int K = 5 ;
System.out.println(findCount(root, K));
}
}
|
Python3
class Node:
def __init__( self , data):
self .data = data
self .left = None
self .right = None
def newNode(data):
newNode = Node(data)
return newNode
def rec(root, res, k):
if (root = = None ):
return [ 0 , res];
xr = root.data;
tmp,res = rec(root.left, res, k);
xr^ = tmp
tmp,res = rec(root.right, res, k);
xr^ = tmp
if (xr = = k):
res + = 1
return xr, res;
def findCount(root, K):
res = 0 ;
tmp,res = rec(root, res, K);
return res;
if __name__ = = '__main__' :
root = newNode( 2 );
root.left = newNode( 1 );
root.right = newNode( 9 );
root.left.left = newNode( 10 );
root.left.right = newNode( 5 );
K = 5 ;
print (findCount(root, K))
|
C#
using System;
public class GFG{
class Node
{
public int data;
public Node left,right;
};
static int res;
static int k;
static Node newNode( int data)
{
Node newNode = new Node();
newNode.data = data;
newNode.left= null ;
newNode.right = null ;
return newNode;
}
static int rec(Node root)
{
if (root == null ) {
return 0;
}
int xr = (root.data);
xr ^= rec(root.left);
xr ^= rec(root.right);
if (xr == k) {
res++;
}
return xr;
}
static int findCount(Node root, int K)
{
res = 0;
k = K;
rec(root);
return res;
}
public static void Main(String []args)
{
Node root = newNode(2);
root.left = newNode(1);
root.right = newNode(9);
root.left.left =newNode(10);
root.left.right = newNode(5);
int K = 5;
Console.WriteLine(findCount(root, K));
}
}
|
Javascript
<script>
class Node
{
constructor()
{
this .data = 0;
this .left = null ;
this .right = null ;
}
};
var res = 0;
var k = 0;
function newNode(data)
{
var newNode = new Node();
newNode.data = data;
newNode.left= null ;
newNode.right = null ;
return newNode;
}
function rec(root)
{
if (root == null ) {
return 0;
}
var xr = (root.data);
xr ^= rec(root.left);
xr ^= rec(root.right);
if (xr == k) {
res++;
}
return xr;
}
function findCount(root, K)
{
res = 0;
k = K;
rec(root);
return res;
}
var root = newNode(2);
root.left = newNode(1);
root.right = newNode(9);
root.left.left =newNode(10);
root.left.right = newNode(5);
var K = 5;
document.write(findCount(root, K));
</script>
|
Performance Analysis:
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).
Approach :
Approach to finding the count of subtrees in a binary tree with XOR value K:
- Create a hash table to store the XOR value of all the nodes encountered so far in the traversal, along with their frequency.
- Perform a pre-order traversal of the binary tree.
- At each node, compute the XOR value of the subtree rooted at that node.
- If the XOR value is equal to K, increment the count.
- Look up the hash table for the frequency of (XOR value – K). Add this frequency to the count.
- Add the XOR value of the current node to the hash table.
- Return the count.
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node *left, *right;
};
struct Node* newNode( int data)
{
struct Node* newNode = new Node;
newNode->data = data;
newNode->left
= newNode->right = NULL;
return (newNode);
}
int rec(Node* root, int & res, int & k)
{
if (root == NULL) {
return 0;
}
int xr = root->data;
xr ^= rec(root->left, res, k);
xr ^= rec(root->right, res, k);
if (xr == k) {
res++;
}
return xr;
}
int findCount(Node* root, int K)
{
int res = 0;
rec(root, res, K);
return res;
}
int main( void )
{
struct Node* root = newNode(2);
root->left = newNode(1);
root->right = newNode(9);
root->left->left = newNode(10);
root->left->right = newNode(5);
int K = 5;
cout << "Count of subtrees having XOR value " << K << " is " << findCount(root, K) << endl;
return 0;
}
|
Java
import java.util.*;
class Node {
int data;
Node left, right;
Node( int item) {
data = item;
left = right = null ;
}
}
public class SubtreeXORCount {
public static int findCount(Node root, int k) {
int [] res = { 0 };
rec(root, res, k);
return res[ 0 ];
}
public static int rec(Node root, int [] res, int k) {
if (root == null ) {
return 0 ;
}
int xr = root.data;
xr ^= rec(root.left, res, k);
xr ^= rec(root.right, res, k);
if (xr == k) {
res[ 0 ]++;
}
return xr;
}
public static void main(String[] args) {
Node root = new Node( 2 );
root.left = new Node( 1 );
root.right = new Node( 9 );
root.left.left = new Node( 10 );
root.left.right = new Node( 5 );
int K = 5 ;
System.out.println( "Count of subtrees having XOR value " + K + " is " + findCount(root, K));
}
}
|
Python3
class Node:
def __init__( self , data):
self .data = data
self .left = None
self .right = None
def rec(root, res, k):
if root is None :
return 0
xr = root.data
xr ^ = rec(root.left, res, k)
xr ^ = rec(root.right, res, k)
if xr = = k:
res[ 0 ] + = 1
return xr
def findCount(root, K):
res = [ 0 ]
rec(root, res, K)
return res[ 0 ]
if __name__ = = "__main__" :
root = Node( 2 )
root.left = Node( 1 )
root.right = Node( 9 )
root.left.left = Node( 10 )
root.left.right = Node( 5 )
K = 5
print ( "Count of subtrees having XOR value" , K, "is" , findCount(root, K))
|
C#
using System;
public class Node
{
public int data;
public Node left, right;
public Node( int data)
{
this .data = data;
this .left = this .right = null ;
}
}
public class BinaryTree
{
public static int FindCount(Node root, int K)
{
int res = 0;
Rec(root, ref res, K);
return res;
}
private static int Rec(Node root, ref int res, int K)
{
if (root == null )
{
return 0;
}
int xr = root.data;
xr ^= Rec(root.left, ref res, K);
xr ^= Rec(root.right, ref res, K);
if (xr == K)
{
res++;
}
return xr;
}
public static void Main()
{
Node root = new Node(2);
root.left = new Node(1);
root.right = new Node(9);
root.left.left = new Node(10);
root.left.right = new Node(5);
int K = 5;
Console.WriteLine( "Count of subtrees having XOR value " + K + " is " + FindCount(root, K));
}
}
|
Javascript
class Node {
constructor(item) {
this .data = item;
this .left = null ;
this .right = null ;
}
}
class SubtreeXORCount {
static findCount(root, k) {
let res = [0];
SubtreeXORCount.rec(root, res, k);
return res[0];
}
static rec(root, res, k) {
if (root === null ) {
return 0;
}
let xr = root.data;
xr ^= SubtreeXORCount.rec(root.left, res, k);
xr ^= SubtreeXORCount.rec(root.right, res, k);
if (xr === k) {
res[0]++;
}
return xr;
}
static main() {
let root = new Node(2);
root.left = new Node(1);
root.right = new Node(9);
root.left.left = new Node(10);
root.left.right = new Node(5);
let K = 5;
console.log( "Count of subtrees having XOR value " + K + " is " + SubtreeXORCount.findCount(root, K));
}
}
SubtreeXORCount.main();
|
Output
Count of subtrees having XOR value 5 is 2
Performance Analysis:
Time complexity: O(n^2) in the worst case, where n is the number of nodes in the binary tree.
Space complexity: O(h), where h is the height of the binary tree.
Similar Reads
Count of subtrees in a Binary Tree having bitwise OR value K
Given a value K and a binary tree, the task is to find out the number of subtrees having bitwise OR of all its elements equal to K. Examples: Input: K = 5, Tree = 2 / \ 1 1 / \ \ 10 5 4 Output: 2 Explanation: Subtree 1: 5 It has only one element i.e. 5. So bitwise OR of subtree = 5 Subtree 2: 1 \ 4
8 min read
Convert given binary tree to a XOR tree
Given a Binary Tree where each node has a value of either 0 or 1, the task is to convert the given Binary tree to an XOR tree i.e a tree such that each node value is the logical XOR between its children. Note: Leaf nodes and nodes with one child are not considered as they don't have both children. E
8 min read
Count of duplicate Subtrees in an N-ary Tree
Given the root of an n-ary tree, the task is to find the number of subtrees that have duplicates in the n-ary tree. Two trees are duplicates if they have the same structure with the same node values. Examples: Input: 1 N 2 2 3 N 4 N 4 4 3 N N N N NOutput: 2Explanation: [4], [3] are duplicate subtree
6 min read
Count pairs in a binary tree whose sum is equal to a given value x
Given a binary tree containing n distinct numbers and a value x. The problem is to count pairs in the given binary tree whose sum is equal to the given value x. Examples: Input : 5 / \ 3 7 / \ / \ 2 4 6 8 x = 10 Output : 3 The pairs are (3, 7), (2, 8) and (4, 6). 1) Naive Approach: One by one get ea
15+ min read
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 /
7 min read
Count no. of ordered subsets having a particular XOR value
Given an array arr[] of n elements and a number K, find the number of ordered subsets of arr[] having XOR of elements as K This is a modified version of this problem. So it is recommended to try that problem before.Examples: Input: arr[] = {6, 9, 4, 2}, k = 6 Output: 2 The subsets are {4, 2}, {2, 4}
11 min read
Count of Fibonacci paths in a Binary tree
Given a Binary Tree, the task is to count the number of Fibonacci paths in the given Binary Tree. Fibonacci Path is a path which contains all nodes in root to leaf path are terms of Fibonacci series. Example: Input: 0 / \ 1 1 / \ / \ 1 10 70 1 / \ 81 2 Output: 2 Explanation: There are 2 Fibonacci pa
10 min read
Count of 1's in any path in a Binary Tree
Given a binary tree of 0s and 1s, the task is to find the maximum number of 1s in any path in the tree. The path may start and end at any node in the tree.Example: Input: 1 / \ 0 1 / \ 1 1 / \ 1 0 Output: 4 Approach: A function countUntil has been created which returns the maximum count of 1 in any
10 min read
Remove all subtrees consisting only of even valued nodes from a Binary Tree
Given a Binary Tree, the task is to remove all the subtrees that do not contain any odd valued node. Print the Levelorder Traversal of the tree after removal of these subtrees. Note: Print NULL for removed nodes. Examples: Input: Below is the given Tree: 1 \ 2 / \ 8 5Output: 1 NULL 2 NULL 5Explanati
8 min read
Count nodes having smallest value in the path from root to itself in a Binary Tree
Given a Binary Tree, the task is to count the number of nodes in the given Binary Tree such that the path from the root to that node contains node with value greater than or equal to that node. Examples: Input: 6 / \ 7 4 / \ / \ 3 7 1 2 Output: 5 Explanation: Root node 6 is considered as its the onl
8 min read