Print Ancestors of a given node in Binary Tree | A Binary Tree node ; If target is present in tree , then prints the ancestors and returns true , otherwise returns false ; Base case ; If target is present in either left or right subtree of this node , then print this node ; Else return False ; Construct the following binary tree 1 / \ 2 3 / \ 4 5 / 7
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 printAncestors ( root , target ) : NEW_LINE INDENT if root == None : NEW_LINE INDENT return False NEW_LINE DEDENT if root . data == target : NEW_LINE INDENT return True NEW_LINE DEDENT if ( printAncestors ( root . left , target ) or printAncestors ( root . right , target ) ) : NEW_LINE INDENT print root . data , NEW_LINE return True NEW_LINE DEDENT return False NEW_LINE DEDENT root = Node ( 1 ) NEW_LINE root . left = Node ( 2 ) NEW_LINE root . right = Node ( 3 ) NEW_LINE root . left . left = Node ( 4 ) NEW_LINE root . left . right = Node ( 5 ) NEW_LINE root . left . left . left = Node ( 7 ) NEW_LINE printAncestors ( root , 7 ) NEW_LINE