Sum of Bitwise AND of the sum of all leaf and non | C # 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
using System ; using System . Collections . Generic ; class GFG { class TreeNode { public int val ; public TreeNode left , right ; } ; static TreeNode newNode ( int x ) { TreeNode temp = new TreeNode ( ) ; temp . val = x ; temp . left = null ; temp . right = null ; return temp ; } static int findSum ( TreeNode root ) { Queue < TreeNode > que = new Queue < TreeNode > ( ) ; que . Enqueue ( root ) ; int ans = 0 ; while ( que . Count > 0 ) { int leaf = 0 ; int nonleaf = 0 ; int length = que . Count ; while ( length > 0 ) { TreeNode temp = que . Peek ( ) ; que . Dequeue ( ) ; if ( temp . left == null && temp . right == null ) leaf += temp . val ; else nonleaf += temp . val ; if ( temp . left != null ) que . Enqueue ( temp . left ) ; if ( temp . right != null ) que . Enqueue ( temp . right ) ; length -= 1 ; } ans += ( leaf & nonleaf ) ; } return ans ; } public static void Main ( ) { TreeNode root = newNode ( 5 ) ; root . left = newNode ( 3 ) ; root . right = newNode ( 9 ) ; root . left . left = newNode ( 6 ) ; root . left . right = newNode ( 4 ) ; root . left . left . right = newNode ( 7 ) ; Console . WriteLine ( findSum ( root ) ) ; } }