Queries to calculate Bitwise OR of each subtree of a given node in an N | 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 ; Number of nodes ; Function call
const N = 1e5 + 5 ; let adj = [ ] ; for ( let i = 0 ; i < N ; i ++ ) { adj . push ( [ ] ) } let answer = new Array ( N ) ; function addEdgesToGraph ( Edges , N ) { for ( let i = 0 ; i < N - 1 ; i ++ ) { let u = Edges [ i ] [ 0 ] ; let v = Edges [ i ] [ 1 ] ; adj [ u ] . push ( v ) ; adj [ v ] . push ( u ) ; } } function DFS ( node , parent , Val ) { answer [ node ] = Val [ node ] ; for ( let child of adj [ node ] ) { if ( child == parent ) continue ; DFS ( child , node , Val ) ; answer [ node ] = ( answer [ node ] answer [ child ] ) ; } } function preprocess ( Val ) { DFS ( 1 , - 1 , Val ) ; } function findSubtreeOR ( Queries , Q , Val ) { preprocess ( Val ) ; for ( let i = 0 ; i < Q ; i ++ ) { document . write ( answer [ Queries [ i ] ] + ' ' ) ; } } function findSubtreeORUtil ( N , Edges , Val , Queries , Q ) { addEdgesToGraph ( Edges , N ) ; findSubtreeOR ( Queries , Q , Val ) ; } let n = 5 ; let Edges = [ [ 1 , 2 ] , [ 1 , 3 ] , [ 3 , 4 ] , [ 3 , 5 ] ] ; let Val = [ 0 , 2 , 3 , 4 , 8 , 16 ] ; let Queries = [ 2 , 3 , 1 ] ; let Q = Queries . length ; findSubtreeORUtil ( n , Edges , Val , Queries , Q ) ;