Sum of decimal equivalents of binary node values in each level of a Binary Tree | C # 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
using System ; using System . Collections . Generic ; class GFG { class TreeNode { public int val ; public TreeNode left , right ; } ; static TreeNode newNode ( int key ) { TreeNode temp = new TreeNode ( ) ; temp . val = key ; temp . left = temp . right = null ; return temp ; } static int convertBinaryToDecimal ( List < int > arr ) { int ans = 0 ; foreach ( int i in arr ) ans = ( ans << 1 ) | i ; return ans ; } static void decimalEquilvalentAtEachLevel ( TreeNode root ) { int ans = 0 ; Queue < TreeNode > que = new Queue < TreeNode > ( ) ; que . Enqueue ( root ) ; while ( true ) { int length = que . Count ; if ( length == 0 ) break ; List < int > eachLvl = new List < int > ( ) ; while ( length > 0 ) { TreeNode temp = que . Peek ( ) ; que . Dequeue ( ) ; eachLvl . Add ( temp . val ) ; if ( temp . left != null ) que . Enqueue ( temp . left ) ; if ( temp . right != null ) que . Enqueue ( temp . right ) ; length -= 1 ; } ans += convertBinaryToDecimal ( eachLvl ) ; } Console . WriteLine ( ans ) ; } public static void Main ( ) { TreeNode root = newNode ( 0 ) ; root . left = newNode ( 1 ) ; root . right = newNode ( 0 ) ; root . left . left = newNode ( 0 ) ; root . left . right = newNode ( 1 ) ; root . right . left = newNode ( 1 ) ; root . right . right = newNode ( 1 ) ; decimalEquilvalentAtEachLevel ( root ) ; } }