Sum of nodes at maximum depth of a Binary Tree | 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
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def sumMaxLevelRec ( node , Max ) : NEW_LINE INDENT if node == None : NEW_LINE INDENT return 0 NEW_LINE DEDENT if Max == 1 : NEW_LINE INDENT return node . data NEW_LINE DEDENT return ( sumMaxLevelRec ( node . left , Max - 1 ) + sumMaxLevelRec ( node . right , Max - 1 ) ) NEW_LINE DEDENT def maxDepth ( node ) : NEW_LINE INDENT if node == None : NEW_LINE INDENT return 0 NEW_LINE DEDENT return 1 + max ( maxDepth ( node . left ) , maxDepth ( node . right ) ) NEW_LINE DEDENT def sumMaxLevel ( root ) : NEW_LINE INDENT MaxDepth = maxDepth ( root ) NEW_LINE return sumMaxLevelRec ( root , MaxDepth ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT root = Node ( 1 ) NEW_LINE root . left = Node ( 2 ) NEW_LINE root . right = Node ( 3 ) NEW_LINE root . left . left = Node ( 4 ) NEW_LINE root . left . right = Node ( 5 ) NEW_LINE root . right . left = Node ( 6 ) NEW_LINE root . right . right = Node ( 7 ) NEW_LINE print ( sumMaxLevel ( root ) ) NEW_LINE DEDENT