Python program to query for ancestor-descendant relationship in a tree














































Python program to query for ancestor-descendant relationship in a tree



Description:
  1. Given a binary tree.
  2. We are given two nodes and we need to find the relationship between them.
  3. That is whether 1st node is an ancestor or not of the 2nd node.



l = []
#stores the ancestors of a given descendant node #class for creating a binary tree class Node: def __init__(self,data): self.data = data self.left = None self.right = None #function for checking the ancestors of given descendant def ancestors(root, target): if root == None: return False if root.data == target: return True if (ancestors(root.left, target) or ancestors(root.right,target)): l.append(root.data) return True return False #implementing a binary tree root = Node(0) root.left = Node(1) root.right = Node(2) root.left.left = Node(3) root.left.right = Node(4) root.right.right = Node(5) root.left.right.left = Node(6) root.right.right.left = Node(7) x = int(input("Enter ancestor node: ")) y = int(input("Enter descendant node: ")) ancestors(root,y) if(x in l): print("Yes") else: print("No")




Output:
Enter ancestor node: 1
Enter descendant node: 6
Yes

Enter ancestor node: 1
Enter descendant node: 7
No


Comments