Print path from root to a given node in a binary tree | Helper Class that allocates a new node with the given data and None left and right pointers . ; Returns true if there is a path from root to the given node . It also populates ' arr ' with the given path ; if root is None there is no path ; push the node ' s ▁ value ▁ in ▁ ' arr '  ; if it is the required node return true ; else check whether the required node lies in the left subtree or right subtree of the current node ; required node does not lie either in the left or right subtree of the current node . Thus , remove current node ' s ▁ value ▁ ▁ ▁ from ▁ ' arr 'and then return false  ; function to print the path from root to the given node if the node lies in the binary tree ; vector to store the path ; if required node ' x ' is present then print the path ; ' x ' is not present in the binary tree ; Driver Code ; binary tree formation
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 hasPath ( root , arr , x ) : NEW_LINE INDENT if ( not root ) : NEW_LINE INDENT return False NEW_LINE DEDENT arr . append ( root . data ) NEW_LINE if ( root . data == x ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( hasPath ( root . left , arr , x ) or hasPath ( root . right , arr , x ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT arr . pop ( - 1 ) NEW_LINE return False NEW_LINE DEDENT def printPath ( root , x ) : NEW_LINE INDENT arr = [ ] NEW_LINE if ( hasPath ( root , arr , x ) ) : NEW_LINE INDENT for i in range ( len ( arr ) - 1 ) : NEW_LINE INDENT print ( arr [ i ] , end = " - > " ) NEW_LINE DEDENT print ( arr [ len ( arr ) - 1 ] ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No ▁ Path " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = getNode ( 1 ) NEW_LINE root . left = getNode ( 2 ) NEW_LINE root . right = getNode ( 3 ) NEW_LINE root . left . left = getNode ( 4 ) NEW_LINE root . left . right = getNode ( 5 ) NEW_LINE root . right . left = getNode ( 6 ) NEW_LINE root . right . right = getNode ( 7 ) NEW_LINE x = 5 NEW_LINE printPath ( root , x ) NEW_LINE DEDENT