Count of subtrees in a Binary Tree having XOR value K | Java program to find the count of subtrees in a Binary Tree having XOR value K ; A binary tree node ; A utility function to allocate a new node ; Base Case : If node is null , return 0 ; Calculating the XOR of the current subtree int xr = ( root . data ) ; ^ rec ( root . left ) ^ rec ( root . right ) ; ; Increment res if xr is equal to k ; Return the XOR value of the current subtree ; Function to find the required count ; Initialize result variable ' res ' ; Recursively traverse the tree and compute the count ; return the count ' res ' ; Driver program ; Create the binary tree by adding nodes to it
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 ; } 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 ) ) ; } }