Check sum of Covered and Uncovered nodes of Binary Tree | A binary tree node has key , pointer to left child and a pointer to right child ; Utility function to calculate sum of all node of tree ; Recursive function to calculate sum of left boundary elements ; If left node , then just return its key value ; If left is available then go left otherwise go right ; Recursive function to calculate sum of right boundary elements ; If left node , then just return its key value ; If right is available then go right otherwise go left ; Returns sum of uncovered elements ; Initializing with 0 in case we don 't have  left or right boundary  ; returning sum of root node , left boundary and right boundary ; Returns true if sum of covered and uncovered elements is same . ; Sum of uncovered elements ; Sum of all elements ; Check if sum of covered and uncovered is same ; Helper function to print inorder traversal of binary tree ; Driver program to test above functions ; Making above given diagram 's binary tree
class Node { int key ; Node left , right ; public Node ( int key ) { this . key = key ; left = right = null ; } } class BinaryTree { Node root ; int sum ( Node t ) { if ( t == null ) return 0 ; return t . key + sum ( t . left ) + sum ( t . right ) ; } int uncoveredSumLeft ( Node t ) { if ( t . left == null && t . right == null ) return t . key ; if ( t . left != null ) return t . key + uncoveredSumLeft ( t . left ) ; else return t . key + uncoveredSumLeft ( t . right ) ; } int uncoveredSumRight ( Node t ) { if ( t . left == null && t . right == null ) return t . key ; if ( t . right != null ) return t . key + uncoveredSumRight ( t . right ) ; else return t . key + uncoveredSumRight ( t . left ) ; } int uncoverSum ( Node t ) { int lb = 0 , rb = 0 ; if ( t . left != null ) lb = uncoveredSumLeft ( t . left ) ; if ( t . right != null ) rb = uncoveredSumRight ( t . right ) ; return t . key + lb + rb ; } boolean isSumSame ( Node root ) { int sumUC = uncoverSum ( root ) ; int sumT = sum ( root ) ; return ( sumUC == ( sumT - sumUC ) ) ; } void inorder ( Node root ) { if ( root != null ) { inorder ( root . left ) ; System . out . print ( root . key + " ▁ " ) ; inorder ( root . right ) ; } } public static void main ( String [ ] args ) { BinaryTree tree = new BinaryTree ( ) ; tree . root = new Node ( 8 ) ; tree . root . left = new Node ( 3 ) ; tree . root . left . left = new Node ( 1 ) ; tree . root . left . right = new Node ( 6 ) ; tree . root . left . right . left = new Node ( 4 ) ; tree . root . left . right . right = new Node ( 7 ) ; tree . root . right = new Node ( 10 ) ; tree . root . right . right = new Node ( 14 ) ; tree . root . right . right . left = new Node ( 13 ) ; if ( tree . isSumSame ( tree . root ) ) System . out . println ( " Sum ▁ of ▁ covered ▁ and ▁ uncovered ▁ is ▁ same " ) ; else System . out . println ( " Sum ▁ of ▁ covered ▁ and ▁ uncovered ▁ is ▁ not ▁ same " ) ; } }