Maximize count of set bits in a root to leaf path in a binary tree | JavaScript Program to implement the above approach ; Node structure ; Initialize constructor ; Function to find the maximum count of setbits in a root to leaf ; Check if root is not null ; Update the maximum count of setbits ; Traverse left of binary tree ; Traverse right of the binary tree ; Driver Code
let maxm = 0 ; class Node { constructor ( x ) { this . val = x ; this . left = null ; this . right = null ; } } var root ; function maxm_setbits ( root , ans ) { if ( ! root ) return ; if ( root . left == null && root . right == null ) { ans += ( root . val ) . toString ( 2 ) . split ( ' ' ) . filter ( y => y == ' ' ) . length ; maxm = Math . max ( ans , maxm ) ; return ; } maxm_setbits ( root . left , ans + ( root . val ) . toString ( 2 ) . split ( ' ' ) . filter ( y => y == ' ' ) . length ) ; maxm_setbits ( root . right , ans + ( root . val ) . toString ( 2 ) . split ( ' ' ) . filter ( y => y == ' ' ) . length ) ; } root = new Node ( 15 ) ; root . left = new Node ( 3 ) ; root . right = new Node ( 7 ) ; root . left . left = new Node ( 5 ) ; root . left . right = new Node ( 1 ) ; root . right . left = new Node ( 31 ) ; root . right . right = new Node ( 9 ) ; maxm_setbits ( root , 0 ) ; document . write ( maxm ) ;