Sum of Bitwise AND of the sum of all leaf and non | Java program for given approach ; 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 ; Driver Code ; Given Tree ; Function Call
import java . util . * ; class GFG { static class TreeNode { int val ; TreeNode left , right ; TreeNode ( int x ) { val = x ; left = null ; right = null ; } } ; static int findSum ( TreeNode root ) { Queue < TreeNode > que = new LinkedList < > ( ) ; que . add ( root ) ; int ans = 0 ; while ( que . size ( ) > 0 ) { int leaf = 0 ; int nonleaf = 0 ; int length = que . size ( ) ; while ( length > 0 ) { TreeNode temp = que . peek ( ) ; que . remove ( ) ; if ( temp . left == null && temp . right == null ) leaf += temp . val ; else nonleaf += temp . val ; if ( temp . left != null ) que . add ( temp . left ) ; if ( temp . right != null ) que . add ( temp . right ) ; length -= 1 ; } ans += leaf & nonleaf ; } return ans ; } public static void main ( String [ ] args ) { TreeNode root = new TreeNode ( 5 ) ; root . left = new TreeNode ( 3 ) ; root . right = new TreeNode ( 9 ) ; root . left . left = new TreeNode ( 6 ) ; root . left . right = new TreeNode ( 4 ) ; root . left . left . right = new TreeNode ( 7 ) ; System . out . print ( findSum ( root ) ) ; } }