Maximize count of set bits in a root to leaf path in a binary tree | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxm = 0 ; struct Node { int val ; Node * left , * right ; Node ( int x ) { val = x ; left = NULL ; right = NULL ; } } ; void maxm_setbits ( Node * root , int ans ) { if ( ! root ) return ; if ( root -> left == NULL && root -> right == NULL ) { ans += __builtin_popcount ( root -> val ) ; maxm = max ( ans , maxm ) ; return ; } maxm_setbits ( root -> left , ans + __builtin_popcount ( root -> val ) ) ; maxm_setbits ( root -> right , ans + __builtin_popcount ( root -> val ) ) ; } int main ( ) { 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 ) ; cout << maxm << endl ; return 0 ; }