Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # https://code2begin.blogspot.com
- # program to print all ancestors of a given node in a binary tree
- # node class
- class node:
- def __init__(self, element):
- self.data = element
- self.left = None
- self.right = None
- # function to print all the ancestors of a node
- def ancestors(root, target):
- # if the current node is null then return False
- if root is None:
- return False
- # if the current node is our target node then we return True
- if root.data == target:
- return True
- # here we recursively check if the current node if the ancestor of the target node then we need to print it
- # the target node might lie in the left or the right subtree
- # thus we take or of the the returned boolean values
- if ancestors(root.left, target) or ancestors(root.right, target):
- print(root.data, end=" ")
- return True
- return False
- head = node(1)
- head.left = node(2)
- head.right = node(3)
- head.left.left = node(4)
- head.left.right = node(5)
- head.right.right = node(6)
- head.left.left.right = node(7)
- head.right.right.left = node(8)
- head.left.left.right.left = node(9)
- head.left.left.right.left.left = node(10)
- head.right.right.left.right = node(11)
- print("All ancestors of node 10 are : ")
- ancestors(head, 10)
- print("\nAll ancestors of node 5 are : ")
- ancestors(head, 5)
- print("\nAll ancestors of node 8 are : ")
- ancestors(head, 8)
Add Comment
Please, Sign In to add comment