Sum of decimal equivalents of binary node values in each level of a Binary Tree | CPP program for the above approach ; Structure of a Tree Node ; Function to convert binary number to its equivalent decimal value ; Function to calculate sum of decimal equivalent of binary numbers of node values present at each level ; Push root node into queue ; Connect nodes at the same level to form a binary number ; Append the value of the current node to eachLvl ; Insert the Left child to queue , if its not NULL ; Insert the Right child to queue , if its not NULL ; Decrement length by one ; Stores the front element of the queue ; Add decimal equivalent of the binary number formed on the current level to ans ; Finally print ans ; Driver Code ; Given Tree ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; class TreeNode { public : int val ; TreeNode * left , * right ; TreeNode ( int key ) { val = key ; left = right = NULL ; } } ; int convertBinaryToDecimal ( vector < int > arr ) { int ans = 0 ; for ( int i : arr ) ans = ( ans << 1 ) | i ; return ans ; } void decimalEquilvalentAtEachLevel ( TreeNode * root ) { int ans = 0 ; queue < TreeNode * > que ; que . push ( root ) ; while ( true ) { int length = que . size ( ) ; if ( length == 0 ) break ; vector < int > eachLvl ; while ( length > 0 ) { TreeNode * temp = que . front ( ) ; que . pop ( ) ; eachLvl . push_back ( temp -> val ) ; if ( temp -> left != NULL ) que . push ( temp -> left ) ; if ( temp -> right != NULL ) que . push ( temp -> right ) ; length -= 1 ; } ans += convertBinaryToDecimal ( eachLvl ) ; } cout << ans << endl ; } int main ( ) { TreeNode * root = new TreeNode ( 0 ) ; root -> left = new TreeNode ( 1 ) ; root -> right = new TreeNode ( 0 ) ; root -> left -> left = new TreeNode ( 0 ) ; root -> left -> right = new TreeNode ( 1 ) ; root -> right -> left = new TreeNode ( 1 ) ; root -> right -> right = new TreeNode ( 1 ) ; decimalEquilvalentAtEachLevel ( root ) ; return 0 ; }