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 ; Stores the front element of the queue ; 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 ; Add decimal equivalent of the binary number formed on the current level to ans ; Finally print ans ; Given Tree ; Function Call
class TreeNode : NEW_LINE INDENT def __init__ ( self , val = 0 , left = None , right = None ) : NEW_LINE INDENT self . val = val NEW_LINE self . left = left NEW_LINE self . right = right NEW_LINE DEDENT DEDENT def convertBinaryToDecimal ( arr ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in arr : NEW_LINE INDENT ans = ( ans << 1 ) | i NEW_LINE DEDENT return ans NEW_LINE DEDENT def decimalEquilvalentAtEachLevel ( root ) : NEW_LINE INDENT ans = 0 NEW_LINE que = [ root ] NEW_LINE while True : NEW_LINE INDENT length = len ( que ) NEW_LINE if not length : NEW_LINE INDENT break NEW_LINE DEDENT eachLvl = [ ] NEW_LINE while length : NEW_LINE INDENT temp = que . pop ( 0 ) NEW_LINE eachLvl . append ( temp . val ) NEW_LINE if temp . left : NEW_LINE INDENT que . append ( temp . left ) NEW_LINE DEDENT if temp . right : NEW_LINE INDENT que . append ( temp . right ) NEW_LINE DEDENT length -= 1 NEW_LINE DEDENT ans += convertBinaryToDecimal ( eachLvl ) NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT root = TreeNode ( 0 ) NEW_LINE root . left = TreeNode ( 1 ) NEW_LINE root . right = TreeNode ( 0 ) NEW_LINE root . left . left = TreeNode ( 0 ) NEW_LINE root . left . right = TreeNode ( 1 ) NEW_LINE root . right . left = TreeNode ( 1 ) NEW_LINE root . right . right = TreeNode ( 1 ) NEW_LINE decimalEquilvalentAtEachLevel ( root ) NEW_LINE