Sum of decimal equivalents of binary node values in each level of a Binary Tree | 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 ; Given Tree ; Function Call
class TreeNode { constructor ( ) { this . val = 0 ; this . left = null ; this . right = null ; } } ; function newNode ( key ) { var temp = new TreeNode ( ) ; temp . val = key ; temp . left = temp . right = null ; return temp ; } function convertBinaryToDecimal ( arr ) { var ans = 0 ; for ( var i of arr ) ans = ( ans << 1 ) | i ; return ans ; } function decimalEquilvalentAtEachLevel ( root ) { var ans = 0 ; var que = [ ] ; que . push ( root ) ; while ( true ) { var length = que . length ; if ( length == 0 ) break ; var eachLvl = [ ] ; while ( length > 0 ) { var temp = que [ 0 ] ; que . shift ( ) ; eachLvl . push ( temp . val ) ; if ( temp . left != null ) que . push ( temp . left ) ; if ( temp . right != null ) que . push ( temp . right ) ; length -= 1 ; } ans += convertBinaryToDecimal ( eachLvl ) ; } document . write ( ans ) ; } var 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 ) ;