Queries to calculate Bitwise OR of each subtree of a given node in an N | Java program for above approach ; Maximum Number of nodes ; Adjacency list ; Stores Bitwise OR of each node ; Function to add edges to the Tree ; Traverse the edges ; Add edges ; Function to perform DFS Traversal on the given tree ; Initialize answer with bitwise OR of current node ; Iterate over each child of the current node ; Skip parent node ; Call DFS for each child ; Taking bitwise OR of the answer of the child to find node 's OR value ; Function to call DFS from the '=  root for precomputing answers ; Function to calculate and print the Bitwise OR for Q queries ; Perform preprocessing ; Iterate over each given query ; Utility function to find and print bitwise OR for Q queries ; Function to add edges to graph ; Function call ; Driver function ; Number of nodes ; Function call
import java . util . * ; import java . lang . * ; import java . io . * ; class GFG { static int N = ( int ) 1e5 + 5 ; static ArrayList < ArrayList < Integer > > adj ; static int [ ] answer ; static void addEdgesToGraph ( int Edges [ ] [ ] , int N ) { for ( int i = 0 ; i < N - 1 ; i ++ ) { int u = Edges [ i ] [ 0 ] ; int v = Edges [ i ] [ 1 ] ; adj . get ( u ) . add ( v ) ; adj . get ( v ) . add ( u ) ; } } static void DFS ( int node , int parent , int Val [ ] ) { answer [ node ] = Val [ node ] ; for ( Integer child : adj . get ( node ) ) { if ( child == parent ) continue ; DFS ( child , node , Val ) ; answer [ node ] = ( answer [ node ] answer [ child ] ) ; } } static void preprocess ( int Val [ ] ) { DFS ( 1 , - 1 , Val ) ; } static void findSubtreeOR ( int Queries [ ] , int Q , int Val [ ] ) { preprocess ( Val ) ; for ( int i = 0 ; i < Q ; i ++ ) { System . out . println ( answer [ Queries [ i ] ] + " ▁ " ) ; } } static void findSubtreeORUtil ( int N , int Edges [ ] [ ] , int Val [ ] , int Queries [ ] , int Q ) { addEdgesToGraph ( Edges , N ) ; findSubtreeOR ( Queries , Q , Val ) ; } public static void main ( String [ ] args ) { adj = new ArrayList < > ( ) ; for ( int i = 0 ; i < N ; i ++ ) adj . add ( new ArrayList < > ( ) ) ; answer = new int [ N ] ; N = 5 ; int Edges [ ] [ ] = { { 1 , 2 } , { 1 , 3 } , { 3 , 4 } , { 3 , 5 } } ; int Val [ ] = { 0 , 2 , 3 , 4 , 8 , 16 } ; int Queries [ ] = { 2 , 3 , 1 } ; int Q = Queries . length ; findSubtreeORUtil ( N , Edges , Val , Queries , Q ) ; } }