Sum of decimal equivalents of binary node values in each level of a Binary Tree | Java 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
import java . util . ArrayList ; import java . util . LinkedList ; import java . util . Queue ; class GFG { static class TreeNode { int val ; TreeNode left , right ; public TreeNode ( int key ) { val = key ; left = right = null ; } } static int convertBinaryToDecimal ( ArrayList < Integer > arr ) { int ans = 0 ; for ( int i : arr ) ans = ( ans << 1 ) | i ; return ans ; } static void decimalEquilvalentAtEachLevel ( TreeNode root ) { int ans = 0 ; Queue < TreeNode > que = new LinkedList < > ( ) ; que . add ( root ) ; while ( true ) { int length = que . size ( ) ; if ( length == 0 ) break ; ArrayList < Integer > eachLvl = new ArrayList < > ( ) ; while ( length > 0 ) { TreeNode temp = que . poll ( ) ; eachLvl . add ( temp . val ) ; if ( temp . left != null ) que . add ( temp . left ) ; if ( temp . right != null ) que . add ( temp . right ) ; length -= 1 ; } ans += convertBinaryToDecimal ( eachLvl ) ; } System . out . println ( ans ) ; } public static void main ( String [ ] args ) { 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 ) ; } }