Open In App

Count of subtrees in a Binary Tree having XOR value K

Last Updated : 29 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 :

  1. Traverse the tree recursively using pre-order traversal.
  2. 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)

  1.  
  2. If the XOR of any subtree is K, increment the counter variable.
  3. Print the value in counter as the required count

Below is the implementation of the above approach: 

C++




// C++ program to find the count of
// subtrees in a Binary Tree
// having XOR value K
 
#include <bits/stdc++.h>
using namespace std;
 
// A binary tree node
struct Node {
    int data;
    struct Node *left, *right;
};
 
// A utility function to
// allocate a new node
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)
{
    // Base Case:
    // If node is NULL, return 0
    if (root == NULL) {
        return 0;
    }
 
    // Calculating the XOR
    // of the current subtree
    int xr = root->data;
    xr ^= rec(root->left, res, k);
    xr ^= rec(root->right, res, k);
 
    // Increment res
    // if xr is equal to k
    if (xr == k) {
        res++;
    }
 
    // Return the XOR value
    // of the current subtree
    return xr;
}
 
// Function to find the required count
int findCount(Node* root, int K)
{
    // Initialize result variable 'res'
    int res = 0;
 
    // Recursively traverse the tree
    // and compute the count
    rec(root, res, K);
 
    // return the count 'res'
    return res;
}
 
// Driver program
int main(void)
{
 
    /*
        2
       / \
      1   9
     / \
    10  5
    */
 
    // Create the binary tree
    // by adding nodes to it
    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




// Java program to find the count of
// subtrees in a Binary Tree
// having XOR value K
import java.util.*;
 
class GFG{
 
    // A binary tree node
    static class Node
    {
        int data;
        Node left,right;
    };
    static int res;
    static int k;
 
    // A utility function to
    // allocate a new node
    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)
    {
        // Base Case:
        // If node is null, return 0
        if (root == null) {
            return 0;
        }
     
        // Calculating the XOR
        // of the current subtree
        int xr = (root.data);//^rec(root.left)^rec(root.right);
        xr ^= rec(root.left);
        xr ^= rec(root.right);
         
        // Increment res
        // if xr is equal to k
        if (xr == k) {
            res++;
        }
     
        // Return the XOR value
        // of the current subtree
        return xr;
    }
     
    // Function to find the required count
    static int findCount(Node root, int K)
    {
        // Initialize result variable 'res'
        res = 0;
        k = K;
 
        // Recursively traverse the tree
        // and compute the count
        rec(root);
 
        // return the count 'res'
        return res;
    }
     
    // Driver program
    public static void main(String args[])
    {
     
        /*
            2
        / \
        1 9
        / \
        10 5
        */
     
        // Create the binary tree
        // by adding nodes to it
        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));   
    }
}
 
 
// This code is contributed by AbhiThakur


Python3




# Python3 program to find the count of
# subtrees in a Binary Tree
# having XOR value K
  
# A binary tree node
class Node:
     
    def __init__(self, data):
         
        self.data = data
        self.left = None
        self.right = None
         
# A utility function to
# allocate a new node
def newNode(data):
     
    newNode = Node(data)
    return newNode
 
def rec(root, res, k):
 
    # Base Case:
    # If node is None, return 0
    if (root == None):
        return [0, res];
  
    # Calculating the XOR
    # of the current subtree
    xr = root.data;
    tmp,res = rec(root.left, res, k);
    xr^=tmp
    tmp,res = rec(root.right, res, k);
    xr^=tmp
  
    # Increment res
    # if xr is equal to k
    if (xr == k):
        res += 1
   
    # Return the XOR value
    # of the current subtree
    return xr, res;
 
# Function to find the required count
def findCount(root, K):
 
    # Initialize result variable 'res'
    res = 0;
  
    # Recursively traverse the tree
    # and compute the count
    tmp,res=rec(root, res, K);
  
    # return the count 'res'
    return res;
 
# Driver program
if __name__=='__main__':
  
    '''
        2
       / \
      1   9
     / \
    10  5
    '''
  
    # Create the binary tree
    # by adding nodes to it
    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))
 
# This code is contributed by rutvik_56


C#




// C# program to find the count of
// subtrees in a Binary Tree
// having XOR value K
using System;
 
public class GFG{
  
    // A binary tree node
    class Node
    {
        public int data;
        public Node left,right;
    };
    static int res;
    static int k;
  
    // A utility function to
    // allocate a new node
    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)
    {
        // Base Case:
        // If node is null, return 0
        if (root == null) {
            return 0;
        }
      
        // Calculating the XOR
        // of the current subtree
        int xr = (root.data);//^rec(root.left)^rec(root.right);
        xr ^= rec(root.left);
        xr ^= rec(root.right);
          
        // Increment res
        // if xr is equal to k
        if (xr == k) {
            res++;
        }
      
        // Return the XOR value
        // of the current subtree
        return xr;
    }
      
    // Function to find the required count
    static int findCount(Node root, int K)
    {
        // Initialize result variable 'res'
        res = 0;
        k = K;
  
        // Recursively traverse the tree
        // and compute the count
        rec(root);
  
        // return the count 'res'
        return res;
    }
      
    // Driver program
    public static void Main(String []args)
    {
      
        /*
            2
        / \
        1 9
        / \
        10 5
        */
      
        // Create the binary tree
        // by adding nodes to it
        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));   
    }
}
  
// This code is contributed by sapnasingh4991


Javascript




<script>
  
// JavaScript program to find the count of
// subtrees in a Binary Tree
// having XOR value K
 
// A binary tree node
class Node
{
    constructor()
    {
        this.data = 0;
        this.left = null;
        this.right = null;
    }
};
 
var res = 0;
var k = 0;
 
// A utility function to
// allocate a new node
function newNode(data)
{
    var newNode = new Node();
    newNode.data = data;
    newNode.left= null;
    newNode.right = null;
    return newNode;
}
  
function rec(root)
{
    // Base Case:
    // If node is null, return 0
    if (root == null) {
        return 0;
    }
  
    // Calculating the XOR
    // of the current subtree
    var xr = (root.data);//^rec(root.left)^rec(root.right);
    xr ^= rec(root.left);
    xr ^= rec(root.right);
      
    // Increment res
    // if xr is equal to k
    if (xr == k) {
        res++;
    }
  
    // Return the XOR value
    // of the current subtree
    return xr;
}
  
// Function to find the required count
function findCount(root, K)
{
    // Initialize result variable 'res'
    res = 0;
    k = K;
 
    // Recursively traverse the tree
    // and compute the count
    rec(root);
 
    // return the count 'res'
    return res;
}
  
// Driver program
/*
    2
/ \
1 9
/ \
10 5
*/
 
// Create the binary tree
// by adding nodes to it
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>


Output

2








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:

  1. Create a hash table to store the XOR value of all the nodes encountered so far in the traversal, along with their frequency.
  2. Perform a pre-order traversal of the binary tree.
  3. At each node, compute the XOR value of the subtree rooted at that node.
  4. If the XOR value is equal to K, increment the count.
  5. Look up the hash table for the frequency of (XOR value – K). Add this frequency to the count.
  6. Add the XOR value of the current node to the hash table.
  7. Return the count.

C++




#include <bits/stdc++.h>
using namespace std;
 
// A binary tree node
struct Node {
    int data;
    struct Node *left, *right;
};
 
// A utility function to
// allocate a new node
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)
{
    // Base Case:
    // If node is NULL, return 0
    if (root == NULL) {
        return 0;
    }
 
    // Calculating the XOR
    // of the current subtree
    int xr = root->data;
    xr ^= rec(root->left, res, k);
    xr ^= rec(root->right, res, k);
 
    // Increment res
    // if xr is equal to k
    if (xr == k) {
        res++;
    }
 
    // Return the XOR value
    // of the current subtree
    return xr;
}
 
// Function to find the required count
int findCount(Node* root, int K)
{
    // Initialize result variable 'res'
    int res = 0;
 
    // Recursively traverse the tree
    // and compute the count
    rec(root, res, K);
 
    // return the count 'res'
    return res;
}
 
// Driver program
int main(void)
{
 
    /*
        2
       / \
      1   9
     / \
    10  5
    */
 
    // Create the binary tree
    // by adding nodes to it
    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.*;
 
// A binary tree node
class Node {
    int data;
    Node left, right;
 
    // Constructor to create a new node
    Node(int item) {
        data = item;
        left = right = null;
    }
}
 
public class SubtreeXORCount {
 
    // Utility function to calculate the count of subtrees with XOR value 'k'
    public static int findCount(Node root, int k) {
        int[] res = {0}; // Initialize the result variable 'res'
 
        // Call the recursive helper function
        rec(root, res, k);
 
        // Return the count 'res'
        return res[0];
    }
 
    // Recursive helper function to calculate XOR and count of subtrees
    public static int rec(Node root, int[] res, int k) {
        // Base Case: If the node is null, return 0
        if (root == null) {
            return 0;
        }
 
        // Calculate the XOR of the current subtree
        int xr = root.data;
        xr ^= rec(root.left, res, k);
        xr ^= rec(root.right, res, k);
 
        // Increment 'res' if 'xr' is equal to 'k'
        if (xr == k) {
            res[0]++;
        }
 
        // Return the XOR value of the current subtree
        return xr;
    }
 
    // Driver program
    public static void main(String[] args) {
        /*
            2
           / \
          1   9
         / \
        10  5
        */
 
        // Create the binary tree by adding nodes to it
        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




# A binary tree node
class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
 
def rec(root, res, k):
    # Base Case:
    # If node is None, return 0
    if root is None:
        return 0
 
    # Calculating the XOR
    # of the current subtree
    xr = root.data
    xr ^= rec(root.left, res, k)
    xr ^= rec(root.right, res, k)
 
    # Increment res
    # if xr is equal to k
    if xr == k:
        res[0] += 1
 
    # Return the XOR value
    # of the current subtree
    return xr
 
# Function to find the required count
def findCount(root, K):
    # Initialize result variable 'res'
    res = [0]
 
    # Recursively traverse the tree
    # and compute the count
    rec(root, res, K)
 
    # Return the count 'res'
    return res[0]
 
# Driver program
if __name__ == "__main__":
    """
        2
       / \
      1   9
     / \
    10  5
    """
 
    # Create the binary tree
    # by adding nodes to it
    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;
 
// A binary tree node
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
{
    // A utility function to calculate the count of subtrees
    // with XOR value equal to K
    public static int FindCount(Node root, int K)
    {
        int res = 0; // Initialize the result variable 'res'
        Rec(root, ref res, K); // Recursively traverse the tree and compute the count
        return res; // Return the count 'res'
    }
 
    private static int Rec(Node root, ref int res, int K)
    {
        // Base Case: If node is NULL, return 0
        if (root == null)
        {
            return 0;
        }
 
        // Calculate the XOR of the current subtree
        int xr = root.data;
        xr ^= Rec(root.left, ref res, K);
        xr ^= Rec(root.right, ref res, K);
 
        // Increment res if xr is equal to K
        if (xr == K)
        {
            res++;
        }
 
        // Return the XOR value of the current subtree
        return xr;
    }
 
    // Driver program
    public static void Main()
    {
        /*
            2
           / \
          1   9
         / \
        10  5
        */
 
        // Create the binary tree by adding nodes to it
        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




// A binary tree node
class Node {
    constructor(item) {
        this.data = item;
        this.left = null;
        this.right = null;
    }
}
 
class SubtreeXORCount {
    // Utility function to calculate the count of subtrees with XOR value 'k'
    static findCount(root, k) {
        let res = [0]; // Initialize the result variable 'res'
        // Call the recursive helper function
        SubtreeXORCount.rec(root, res, k);
        // Return the count 'res'
        return res[0];
    }
 
    // Recursive helper function to calculate XOR and count of subtrees
    static rec(root, res, k) {
        // Base Case: If the node is null, return 0
        if (root === null) {
            return 0;
        }
        // Calculate the XOR of the current subtree
        let xr = root.data;
        xr ^= SubtreeXORCount.rec(root.left, res, k);
        xr ^= SubtreeXORCount.rec(root.right, res, k);
        // Increment 'res' if 'xr' is equal to 'k'
        if (xr === k) {
            res[0]++;
        }
        // Return the XOR value of the current subtree
        return xr;
    }
 
    // Driver program
    static main() {
        /*
            2
           / \
          1   9
         / \
        10  5
        */
        // Create the binary tree by adding nodes to it
        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. 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads