Sum of all the numbers that are formed from root to leaf paths | Python program to find sum of all paths from root to leaves A Binary tree node ; Returs sums of all root to leaf paths . The first parameter is root of current subtree , the second paramete "r is value of the number formed by nodes from root to this node ; Base Case ; Update val ; If current node is leaf , return the current value of val ; Recur sum of values for left and right subtree ; A wrapper function over treePathSumUtil ( ) ; Pass the initial value as 0 as ther is nothing above root ; Driver function to test above function
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 treePathsSumUtil ( root , val ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return 0 NEW_LINE DEDENT val = ( val * 10 + root . data ) NEW_LINE if root . left is None and root . right is None : NEW_LINE INDENT return val NEW_LINE DEDENT return ( treePathsSumUtil ( root . left , val ) + treePathsSumUtil ( root . right , val ) ) NEW_LINE DEDENT def treePathsSum ( root ) : NEW_LINE INDENT return treePathsSumUtil ( root , 0 ) NEW_LINE DEDENT root = Node ( 6 ) NEW_LINE root . left = Node ( 3 ) NEW_LINE root . right = Node ( 5 ) NEW_LINE root . left . left = Node ( 2 ) NEW_LINE root . left . right = Node ( 5 ) NEW_LINE root . right . right = Node ( 4 ) NEW_LINE root . left . right . left = Node ( 7 ) NEW_LINE root . left . right . right = Node ( 4 ) NEW_LINE print " Sum ▁ of ▁ all ▁ paths ▁ is " , treePathsSum ( root ) NEW_LINE