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
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct TreeNode { int val ; TreeNode * left , * right ; TreeNode ( int x = 0 ) { val = x ; left = NULL ; right = NULL ; } } ; int findSum ( TreeNode * root ) { queue < TreeNode * > que ; que . push ( root ) ; int ans = 0 ; while ( que . size ( ) ) { int leaf = 0 ; int nonleaf = 0 ; int length = que . size ( ) ; while ( length ) { auto temp = que . front ( ) ; que . pop ( ) ; if ( ! temp -> left && ! temp -> right ) leaf += temp -> val ; else nonleaf += temp -> val ; if ( temp -> left ) que . push ( temp -> left ) ; if ( temp -> right ) que . push ( temp -> right ) ; length -= 1 ; } ans += leaf & nonleaf ; } return ans ; } int main ( ) { 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 ) ; cout << findSum ( root ) ; }