Sum of all the parent nodes having child node x | function to get a new node ; put in the data ; function to find the Sum of all the parent nodes having child node x ; if root == None ; if left or right child of root is ' x ' , then add the root ' s ▁ data ▁ to ▁ ' Sum '  ; recursively find the required parent nodes in the left and right subtree ; utility function to find the Sum of all the parent nodes having child node x ; required Sum of parent nodes ; Driver Code ; binary tree formation 4 ; / \ ; 2 5 ; / \ / \ ; 7 2 2 3
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 SumOfParentOfX ( root , Sum , x ) : NEW_LINE INDENT if ( not root ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( ( root . left and root . left . data == x ) or ( root . right and root . right . data == x ) ) : NEW_LINE INDENT Sum [ 0 ] += root . data NEW_LINE DEDENT SumOfParentOfX ( root . left , Sum , x ) NEW_LINE SumOfParentOfX ( root . right , Sum , x ) NEW_LINE DEDENT def SumOfParentOfXUtil ( root , x ) : NEW_LINE INDENT Sum = [ 0 ] NEW_LINE SumOfParentOfX ( root , Sum , x ) NEW_LINE return Sum [ 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 ( 2 ) NEW_LINE root . right . left = getNode ( 2 ) NEW_LINE root . right . right = getNode ( 3 ) NEW_LINE x = 2 NEW_LINE print ( " Sum ▁ = ▁ " , SumOfParentOfXUtil ( root , x ) ) NEW_LINE DEDENT