Count the number of paths from root to leaf of a Binary tree with given XOR value

Given a value K and a binary tree, we have to find out the total number of paths from the root to leaf nodes having XOR of all its nodes along the path equal to K.
Examples:Â
Input: K = 6
2
/ \
1 4
/ \
10 5
Output: 2
Explanation:
Subtree 1:
2
\
4
This particular path has 2 nodes, 2 and 4
and (2 xor 4) = 6.
Subtree 2:
2
/
1
\
5
This particular path has 3 nodes; 2, 1 and 5
and (2 xor 1 xor 5) = 6.
Approach:Â
To solve the question mentioned above we have to traverse the tree recursively using pre-order traversal. For each node keep calculating the XOR of the path from root till the current node.
Â
XOR of current node’s path = (XOR of the path till the parent) ^ (current node value)
If the node is a leaf node that is left and the right child for the current nodes are NULL then we check if the xor value of the path is K, if it is then we increase the count otherwise we do nothing. Finally, print the value in the count.
Below is the implementation of the above approach:Â
Â
C++
// C++ program to Count the number of// path from the root to leaf of a// Binary tree with given XOR valueÂ
#include <bits/stdc++.h>using namespace std;Â
// Binary tree nodestruct Node {Â Â Â Â int data;Â
    struct Node *left, *right;};Â
// Function to create a new nodestruct Node* newNode(int data){Â Â Â Â struct Node* newNode = new Node;Â
    newNode->data = data;Â
    newNode->left        = newNode->right = NULL;Â
    return (newNode);}Â
void Count(Node* root, int xr, int& res, int& k){Â
    // updating the xor value    // with the xor of the path from    // root to the node    xr = xr ^ root->data;Â
    // check if node is leaf node    if (root->left == NULL && root->right == NULL) {Â
        if (xr == k) {            res++;        }        return;    }Â
    // check if the left    // node exist in the tree    if (root->left != NULL) {        Count(root->left, xr, res, k);    }Â
    // check if the right node    // exist in the tree    if (root->right != NULL) {        Count(root->right, xr, res, k);    }Â
    return;}Â
// Function to find the required countint findCount(Node* root, int K){Â
    int res = 0, xr = 0;Â
    // recursively traverse the tree    // and compute the count    Count(root, xr, res, K);Â
    // return the result    return res;}Â
// Driver codeint main(void){    // Create the binary tree    struct Node* root = newNode(2);    root->left = newNode(1);    root->right = newNode(4);    root->left->left = newNode(10);    root->left->right = newNode(5);Â
    int K = 6;Â
    cout << findCount(root, K);Â
    return 0;} |
Java
// Java program to Count the number of// path from the root to leaf of a// Binary tree with given XOR valueimport java.util.*;Â
class GFG{Â Â // Binary tree nodestatic class Node {Â Â Â Â int data;Â Â Â Â Â Â Node left, right;};static int res, k; Â
// Function to create a new nodestatic Node newNode(int data){    Node newNode = new Node();      newNode.data = data;      newNode.left        = newNode.right = null;      return (newNode);}  static void Count(Node root, int xr){      // updating the xor value    // with the xor of the path from    // root to the node    xr = xr ^ root.data;      // check if node is leaf node    if (root.left == null && root.right == null) {          if (xr == k) {            res++;        }        return;    }      // check if the left    // node exist in the tree    if (root.left != null) {        Count(root.left, xr);    }      // check if the right node    // exist in the tree    if (root.right != null) {        Count(root.right, xr);    }      return;}  // Function to find the required countstatic int findCount(Node root, int K){      int xr = 0;    res = 0;    k = K;Â
    // recursively traverse the tree    // and compute the count    Count(root, xr);      // return the result    return res;}  // Driver codepublic static void main(String[] args){    // Create the binary tree    Node root = newNode(2);    root.left = newNode(1);    root.right = newNode(4);    root.left.left = newNode(10);    root.left.right = newNode(5);      int K = 6;      System.out.print(findCount(root, K));}}Â
// This code is contributed by 29AjayKumar |
Python3
# Python3 program to Count # the number of path from # the root to leaf of a# Binary tree with given XOR valueÂ
# Binary tree nodeclass Node:    def __init__(self, data):               self.data = data        self.left = None        self.right = NoneÂ
def Count(root : Node, Â Â Â Â Â Â Â Â Â Â xr : int) -> None:Â Â Â Â Â Â Â global K, resÂ
    # Updating the xor value    # with the xor of the path from    # root to the node    xr = xr ^ root.dataÂ
    # Check if node is leaf node    if (root.left is None and        root.right is None):        if (xr == K):            res += 1Â
        returnÂ
    # Check if the left    # node exist in the tree    if (root.left):        Count(root.left, xr)Â
    # Check if the right node    # exist in the tree    if (root.right):        Count(root.right, xr)Â
    returnÂ
# Function to find the # required countdef findCount(root : Node) -> int:       global K, res    xr = 0Â
    # Recursively traverse the tree    # and compute the count    Count(root, xr)Â
    # return the result    return resÂ
# Driver codeif __name__ == "__main__":Â
    # Create the binary tree    root = Node(2)    root.left = Node(1)    root.right = Node(4)    root.left.left = Node(10)    root.left.right = Node(5)Â
    K = 6    res = 0    print(findCount(root))Â
# This code is contributed by sanjeev2552 |
C#
// C# program to Count the number of// path from the root to leaf of a// Binary tree with given XOR valueusing System;Â
class GFG{   // Binary tree nodeclass Node {    public int data;       public Node left, right;};static int res, k;   // Function to create a new nodestatic Node newNode(int data){    Node newNode = new Node();       newNode.data = data;       newNode.left        = newNode.right = null;       return (newNode);}   static void Count(Node root, int xr){       // updating the xor value    // with the xor of the path from    // root to the node    xr = xr ^ root.data;       // check if node is leaf node    if (root.left == null && root.right == null) {           if (xr == k) {            res++;        }        return;    }       // check if the left    // node exist in the tree    if (root.left != null) {        Count(root.left, xr);    }       // check if the right node    // exist in the tree    if (root.right != null) {        Count(root.right, xr);    }       return;}   // Function to find the required countstatic int findCount(Node root, int K){       int xr = 0;    res = 0;    k = K;      // recursively traverse the tree    // and compute the count    Count(root, xr);       // return the result    return res;}   // Driver codepublic static void Main(String[] args){    // Create the binary tree    Node root = newNode(2);    root.left = newNode(1);    root.right = newNode(4);    root.left.left = newNode(10);    root.left.right = newNode(5);       int K = 6;       Console.Write(findCount(root, K));}}Â
// This code is contributed by Princi Singh |
Javascript
<script>Â Â // JavaScript program to Count the number of// path from the root to leaf of a// Binary tree with given XOR valueÂ
// Binary tree nodeclass Node {Â
    constructor()    {        this.data = 0;        this.left = null;        this.right = null;    }};Â
var res, k;   // Function to create a new nodefunction newNode(data){    var newNode = new Node();       newNode.data = data;       newNode.left        = newNode.right = null;       return (newNode);}   function Count(root, xr){       // updating the xor value    // with the xor of the path from    // root to the node    xr = xr ^ root.data;       // check if node is leaf node    if (root.left == null && root.right == null) {           if (xr == k) {            res++;        }        return;    }       // check if the left    // node exist in the tree    if (root.left != null) {        Count(root.left, xr);    }       // check if the right node    // exist in the tree    if (root.right != null) {        Count(root.right, xr);    }       return;}   // Function to find the required countfunction findCount(root, K){       var xr = 0;    res = 0;    k = K;      // recursively traverse the tree    // and compute the count    Count(root, xr);       // return the result    return res;}   // Driver code// Create the binary treevar root = newNode(2);root.left = newNode(1);root.right = newNode(4);root.left.left = newNode(10);root.left.right = newNode(5);Â
var K = 6;Â
document.write(findCount(root, K));Â
Â
</script> |
2
Â
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: As in the above approach there is no extra space used, therefore the Auxiliary Space complexity will be O(1).
Â
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



