Sum of nodes at maximum depth of a Binary Tree | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left , * right ; Node ( int data ) { this -> data = data ; this -> left = NULL ; this -> right = NULL ; } } ; 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 ) ; } int maxDepth ( Node * node ) { if ( node == NULL ) return 0 ; return 1 + max ( maxDepth ( node -> left ) , maxDepth ( node -> right ) ) ; } int sumMaxLevel ( Node * root ) { int MaxDepth = maxDepth ( root ) ; return sumMaxLevelRec ( root , MaxDepth ) ; } int main ( ) { 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 ) ; cout << ( sumMaxLevel ( root ) ) << endl ; }