Sum of nodes on the longest path from root to leaf node | function to get a new node ; put in the data ; function to find the Sum of nodes on the longest path from root to leaf node ; if true , then we have traversed a root to leaf path ; update maximum Length and maximum Sum according to the given conditions ; recur for left subtree ; recur for right subtree ; utility function to find the Sum of nodes on the longest path from root to leaf node ; if tree is NULL , then Sum is 0 ; finding the maximum Sum ' maxSum ' for the maximum Length root to leaf path ; required maximum Sum ; Driver Code ; binary tree formation 4 ; / \ ; 2 5 ; / \ / \ ; 7 1 2 3 ; / ; 6
class getNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def SumOfLongRootToLeafPath ( root , Sum , Len , maxLen , maxSum ) : NEW_LINE INDENT if ( not root ) : NEW_LINE INDENT if ( maxLen [ 0 ] < Len ) : NEW_LINE INDENT maxLen [ 0 ] = Len NEW_LINE maxSum [ 0 ] = Sum NEW_LINE DEDENT elif ( maxLen [ 0 ] == Len and maxSum [ 0 ] < Sum ) : NEW_LINE INDENT maxSum [ 0 ] = Sum NEW_LINE DEDENT return NEW_LINE DEDENT SumOfLongRootToLeafPath ( root . left , Sum + root . data , Len + 1 , maxLen , maxSum ) NEW_LINE SumOfLongRootToLeafPath ( root . right , Sum + root . data , Len + 1 , maxLen , maxSum ) NEW_LINE DEDENT def SumOfLongRootToLeafPathUtil ( root ) : NEW_LINE INDENT if ( not root ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT maxSum = [ - 999999999999 ] NEW_LINE maxLen = [ 0 ] NEW_LINE SumOfLongRootToLeafPath ( root , 0 , 0 , maxLen , maxSum ) NEW_LINE return maxSum [ 0 ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = getNode ( 4 ) NEW_LINE root . left = getNode ( 2 ) NEW_LINE root . right = getNode ( 5 ) NEW_LINE root . left . left = getNode ( 7 ) NEW_LINE root . left . right = getNode ( 1 ) NEW_LINE root . right . left = getNode ( 2 ) NEW_LINE root . right . right = getNode ( 3 ) NEW_LINE root . left . right . left = getNode ( 6 ) NEW_LINE print ( " Sum ▁ = ▁ " , SumOfLongRootToLeafPathUtil ( root ) ) NEW_LINE DEDENT