Maximum XOR of Two Numbers in an Array | Set 2 | C # program for the above approach ; Structure of Tree ; Function to insert binary representation of element x in the Tree ; Store the head ; Find the i - th bit ; If curr . left is null ; Update curr to curr . left ; If curr . right is null ; Update curr to curr . right ; Function that finds the maximum Bitwise XOR value for all such pairs ; Head Node of Tree ; Insert each element in tree ; Stores the maximum XOR value ; Traverse the given array ; Stores the XOR with current value arr [ i ] ; Finding ith bit ; Check if the bit is 0 ; If right node exists ; Update the currentXOR ; Check if left node exists ; Update the currentXOR ; Update M to M / 2 for next set bit ; Update the maximum XOR ; Return the maximum XOR found ; Driver Code ; Given array [ ] arr ; Function call
using System ; class GFG { public class node { public node left ; public node right ; } ; static void insert ( int x , node head ) { node curr = head ; for ( int i = 30 ; i >= 0 ; i -- ) { int val = ( x >> i ) & 1 ; if ( val == 0 ) { if ( curr . left == null ) curr . left = new node ( ) ; curr = curr . left ; } else { if ( curr . right == null ) curr . right = new node ( ) ; curr = curr . right ; } } } static int findMaximumXOR ( int [ ] arr , int n ) { node head = new node ( ) ; for ( int i = 0 ; i < n ; i ++ ) { insert ( arr [ i ] , head ) ; } int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int curr_xor = 0 ; int M = ( int ) Math . Pow ( 2 , 30 ) ; node curr = head ; for ( int j = 30 ; j >= 0 ; j -- ) { int val = ( arr [ i ] >> j ) & 1 ; if ( val == 0 ) { if ( curr . right != null ) { curr_xor += M ; curr = curr . right ; } else { curr = curr . left ; } } else { if ( curr . left != null ) { curr_xor += M ; curr = curr . left ; } else { curr = curr . right ; } } M /= 2 ; } ans = Math . Max ( ans , curr_xor ) ; } return ans ; } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 3 , 4 } ; int N = arr . Length ; Console . Write ( findMaximumXOR ( arr , N ) ) ; } }