Find root of the tree where children id sum for every node is given | Javascript : Find root of tree where children sum for every node id is given . ; Every node appears once as an id , and every node except for the root appears once in a sum . So if we subtract all the sums from all the ids , we 're left with the root id.  ; Driver code
const findRoot = ( nodeList ) => { let root = 0 ; nodeList . forEach ( element => root += ( Number ( element [ 0 ] ) - Number ( element [ 1 ] ) ) ) ; return root ; } let nodeList = [ [ 1 , 5 ] , [ 2 , 0 ] , [ 3 , 0 ] , [ 4 , 0 ] , [ 5 , 5 ] , [ 6 , 5 ] ] ; let root = findRoot ( nodeList ) ; document . write ( root ) ;