Maximize count of set bits in a root to leaf path in a binary tree | Java Program to implement the above approach ; Node structure ; Pointers to left and right child ; 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
import java . util . * ; class GFG { static int maxm = 0 ; static class Node { int val ; Node left , right ; Node ( int x ) { val = x ; left = null ; right = null ; } } ; static void maxm_setbits ( Node root , int ans ) { if ( root == null ) return ; if ( root . left == null && root . right == null ) { ans += Integer . bitCount ( root . val ) ; maxm = Math . max ( ans , maxm ) ; return ; } maxm_setbits ( root . left , ans + Integer . bitCount ( root . val ) ) ; maxm_setbits ( root . right , ans + Integer . bitCount ( root . val ) ) ; } public static void main ( String [ ] args ) { Node 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 ) ; System . out . print ( maxm + "NEW_LINE"); } }