Sum of Bitwise AND of the sum of all leaf and non | Structure of a Binary tree node ; Helper function to allocate a new node with the given data and left and right pointers as None ; Function to calculate the sum of bitwise AND of the sum of all leaf nodes and non - leaf nodes for each level ; Initialize a queue and append root to it ; Store the required answer ; Stores the sum of leaf nodes at the current level ; Stores the sum of non - leaf nodes at the current level ; Get the size of the queue ; Iterate for all the nodes in the queue currently ; Dequeue a node from queue ; Check if the node is a leaf node ; If true , update the leaf node sum ; Otherwise , update the non - leaf node sum ; Enqueue left and right children of removed node ; Update the answer ; Return the answer ; 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 findSum ( root ) : NEW_LINE INDENT que = [ root ] NEW_LINE ans = 0 NEW_LINE while ( len ( que ) ) : NEW_LINE INDENT leaf = 0 NEW_LINE nonleaf = 0 NEW_LINE length = len ( que ) NEW_LINE while length : NEW_LINE INDENT temp = que . pop ( 0 ) NEW_LINE if not temp . left and not temp . right : NEW_LINE INDENT leaf += temp . val NEW_LINE DEDENT else : NEW_LINE INDENT nonleaf += temp . val NEW_LINE DEDENT 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 += leaf & nonleaf NEW_LINE DEDENT return ans NEW_LINE DEDENT root = TreeNode ( 5 ) NEW_LINE root . left = TreeNode ( 3 ) NEW_LINE root . right = TreeNode ( 9 ) NEW_LINE root . left . left = TreeNode ( 6 ) NEW_LINE root . left . right = TreeNode ( 4 ) NEW_LINE root . left . left . right = TreeNode ( 7 ) NEW_LINE print ( findSum ( root ) ) NEW_LINE