Sum of leaf nodes at minimum level | Java implementation to find the sum of leaf nodes at minimum level ; structure of a node of binary tree ; function to get a new node ; allocate space ; put in the data ; function to find the sum of leaf nodes at minimum level ; if tree is empty ; if there is only one node ; queue used for level order traversal ; push root node in the queue ' q ' ; count number of nodes in the current level ; traverse the current level nodes ; get front element from ' q ' ; if it is a leaf node ; accumulate data to ' sum ' ; set flag ' f ' to 1 , to signify minimum level for leaf nodes has been encountered ; if top ' s ▁ left ▁ and ▁ right ▁ child ▁ ▁ ▁ exists , ▁ then ▁ push ▁ them ▁ to ▁ ' q ' ; required sum ; Driver Code ; binary tree creation
import java . util . * ; class GFG { static class Node { int data ; Node left , right ; } ; static Node getNode ( int data ) { Node newNode = new Node ( ) ; newNode . data = data ; newNode . left = newNode . right = null ; return newNode ; } static int sumOfLeafNodesAtMinLevel ( Node root ) { if ( root == null ) return 0 ; if ( root . left == null && root . right == null ) return root . data ; Queue < Node > q = new LinkedList < > ( ) ; int sum = 0 ; boolean f = false ; q . add ( root ) ; while ( f == false ) { int nc = q . size ( ) ; while ( nc -- > 0 ) { Node top = q . peek ( ) ; q . remove ( ) ; if ( top . left == null && top . right == null ) { sum += top . data ; f = true ; } else { if ( top . left != null ) q . add ( top . left ) ; if ( top . right != null ) q . add ( top . right ) ; } } } return sum ; } public static void main ( String [ ] args ) { Node root = getNode ( 1 ) ; root . left = getNode ( 2 ) ; root . right = getNode ( 3 ) ; root . left . left = getNode ( 4 ) ; root . left . right = getNode ( 5 ) ; root . right . left = getNode ( 6 ) ; root . right . right = getNode ( 7 ) ; root . left . right . left = getNode ( 8 ) ; root . right . left . right = getNode ( 9 ) ; System . out . println ( " Sum ▁ = ▁ " + sumOfLeafNodesAtMinLevel ( root ) ) ; } }