Sum of nodes at maximum depth of a Binary Tree | Java code for sum of nodes at maximum depth ; Constructor ; function to find the sum of nodes at maximum depth arguments are node and max , where max is to match the depth of node at every call to node , if max will be equal to 1 , means we are at deepest node . ; base case ; max == 1 to track the node at deepest level ; recursive call to left and right nodes ; maxDepth function to find the max depth of the tree ; base case ; either leftDepth of rightDepth is greater add 1 to include height of node at which call is ; call to function to calculate max depth ; Driver code ; Constructing tree ; call to calculate required sum
import java . util . * ; class Node { int data ; Node left , right ; public Node ( int data ) { this . data = data ; this . left = null ; this . right = null ; } } class GfG { public static int sumMaxLevelRec ( Node node , int max ) { if ( node == null ) return 0 ; if ( max == 1 ) return node . data ; return sumMaxLevelRec ( node . left , max - 1 ) + sumMaxLevelRec ( node . right , max - 1 ) ; } public static int maxDepth ( Node node ) { if ( node == null ) return 0 ; return 1 + Math . max ( maxDepth ( node . left ) , maxDepth ( node . right ) ) ; } public static int sumMaxLevel ( Node root ) { int MaxDepth = maxDepth ( root ) ; return sumMaxLevelRec ( root , MaxDepth ) ; } public static void main ( String [ ] args ) { Node root = new Node ( 1 ) ; root . left = new Node ( 2 ) ; root . right = new Node ( 3 ) ; root . left . left = new Node ( 4 ) ; root . left . right = new Node ( 5 ) ; root . right . left = new Node ( 6 ) ; root . right . right = new Node ( 7 ) ; System . out . println ( sumMaxLevel ( root ) ) ; } }