Print the number of set bits in each node of a Binary Tree | CPP program to print the number of set bits in each node of the binary tree ; Binary Tree node ; Utility function that allocates a new Node ; Function to print the number of set bits in each node of the binary tree ; Print the number of set bits of current node using __builtin_popcount ( ) ; Traverse Left Subtree ; Traverse Right Subtree ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left , * right ; } ; Node * newNode ( int data ) { Node * node = new Node ; node -> data = data ; node -> left = node -> right = NULL ; return ( node ) ; } void printSetBit ( Node * root ) { if ( root == NULL ) return ; cout << " Set ▁ bits ▁ in ▁ Node ▁ " << root -> data << " ▁ = ▁ " << __builtin_popcount ( root -> data ) << " STRNEWLINE " ; printSetBit ( root -> left ) ; printSetBit ( root -> right ) ; } int main ( ) { Node * root = newNode ( 16 ) ; root -> left = newNode ( 13 ) ; root -> left -> left = newNode ( 14 ) ; root -> left -> right = newNode ( 12 ) ; root -> right = newNode ( 11 ) ; root -> right -> left = newNode ( 10 ) ; root -> right -> right = newNode ( 16 ) ; printSetBit ( root ) ; return 0 ; }