Queries to calculate Bitwise OR of each subtree of a given node in an N | C # program to generate n - bit Gray codes ; 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
using System ; using System . Collections . Generic ; class GFG { static int N = ( int ) 1e5 + 5 ; static List < List < int > > 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 [ u ] . Add ( v ) ; adj [ v ] . Add ( u ) ; } } static void DFS ( int node , int parent , int [ ] Val ) { answer [ node ] = Val [ node ] ; foreach ( int child in adj [ 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 ++ ) { Console . Write ( 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 List < List < int > > ( ) ; for ( int i = 0 ; i < N ; i ++ ) adj . Add ( new List < int > ( ) ) ; 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 ) ; } }