Sum of nodes at maximum depth of a Binary Tree | Python3 code to find the sum of the nodes which are present at the maximum depth . ; Binary tree node ; Function to find the sum of the node which are present at the maximum depth . While traversing the nodes compare the level of the node with max_level ( Maximum level till the current node ) . If the current level exceeds the maximum level , update the max_level as current level . If the max level and current level are same , add the root data to current sum . ; Driver Code
sum = [ 0 ] NEW_LINE max_level = [ - ( 2 ** 32 ) ] NEW_LINE class createNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . d = data NEW_LINE self . l = None NEW_LINE self . r = None NEW_LINE DEDENT DEDENT def sumOfNodesAtMaxDepth ( ro , level ) : NEW_LINE INDENT if ( ro == None ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( level > max_level [ 0 ] ) : NEW_LINE INDENT sum [ 0 ] = ro . d NEW_LINE max_level [ 0 ] = level NEW_LINE DEDENT elif ( level == max_level [ 0 ] ) : NEW_LINE INDENT sum [ 0 ] = sum [ 0 ] + ro . d NEW_LINE DEDENT sumOfNodesAtMaxDepth ( ro . l , level + 1 ) NEW_LINE sumOfNodesAtMaxDepth ( ro . r , level + 1 ) NEW_LINE DEDENT root = createNode ( 1 ) NEW_LINE root . l = createNode ( 2 ) NEW_LINE root . r = createNode ( 3 ) NEW_LINE root . l . l = createNode ( 4 ) NEW_LINE root . l . r = createNode ( 5 ) NEW_LINE root . r . l = createNode ( 6 ) NEW_LINE root . r . r = createNode ( 7 ) NEW_LINE sumOfNodesAtMaxDepth ( root , 0 ) NEW_LINE print ( sum [ 0 ] ) NEW_LINE