Construct XOR tree by Given leaf nodes of Perfect Binary Tree | Java implementation of the above approach ; Maximum size for xor tree ; Allocating space to xor tree ; A recursive function that constructs xor tree for vector array [ start ... . . end ] . x is index of current node in XOR tree ; If there is one element in vector array , store it in current node of XOR tree ; System . out . print ( xor_tree [ x ] + " ▁ x " ; ; for left subtree ; for right subtree ; for getting the middle index from corner indexes . ; Build the left and the right subtrees by xor operation ; merge the left and right subtrees by XOR operation ; Function to conXOR tree from the given vector array . This function calls construct_Xor_Tree_Util ( ) to fill the allocated memory of xor_tree vector array ; Driver Code ; leaf nodes of Perfect Binary Tree ; Build the xor tree ; Height of xor tree ; Maximum size of xor tree ; Root node is at index 0 considering 0 - based indexing in XOR Tree ; print value at root node
class GFG { static int maxsize = 100005 ; static int [ ] xor_tree = new int [ maxsize ] ; static void construct_Xor_Tree_Util ( int [ ] current , int start , int end , int x ) { if ( start == end ) { xor_tree [ x ] = current [ start ] ; return ; } int left = x * 2 + 1 ; int right = x * 2 + 2 ; int mid = start + ( end - start ) / 2 ; construct_Xor_Tree_Util ( current , start , mid , left ) ; construct_Xor_Tree_Util ( current , mid + 1 , end , right ) ; xor_tree [ x ] = ( xor_tree [ left ] ^ xor_tree [ right ] ) ; } static void construct_Xor_Tree ( int [ ] arr , int n ) { construct_Xor_Tree_Util ( arr , 0 , n - 1 , 0 ) ; } public static void main ( String [ ] args ) { int [ ] leaf_nodes = { 40 , 32 , 12 , 1 , 4 , 3 , 2 , 7 } ; int n = leaf_nodes . length ; construct_Xor_Tree ( leaf_nodes , n ) ; int x = ( int ) ( Math . ceil ( Math . log ( n ) ) ) ; int max_size = 2 * ( int ) Math . pow ( 2 , x ) - 1 ; System . out . print ( "Nodes of the XOR Tree:NEW_LINE"); for ( int i = 0 ; i < max_size ; i ++ ) { System . out . print ( xor_tree [ i ] + " ▁ " ) ; } int root = 0 ; System . out . print ( " Root : " + xor_tree[root]); } }