m2skills

ancestor python

Jun 3rd, 2018
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.35 KB | None | 0 0
  1. # https://code2begin.blogspot.com
  2. # program to print all ancestors of a given node in a binary tree
  3. # node class
  4. class node:
  5.     def __init__(self, element):
  6.         self.data = element
  7.         self.left = None
  8.         self.right = None
  9.  
  10.  
  11.  
  12. # function to print all the ancestors of a node
  13. def ancestors(root, target):
  14.     # if the current node is null then return False
  15.     if root is None:
  16.         return False
  17.  
  18.     # if the current node is our target node then we return True
  19.     if root.data == target:
  20.         return True
  21.  
  22.     # here we recursively check if the current node if the ancestor of the target node then we need to print it
  23.     # the target node might lie in the left or the right subtree
  24.     # thus we take or of the the returned boolean values
  25.     if ancestors(root.left, target) or ancestors(root.right, target):
  26.         print(root.data, end=" ")
  27.         return True
  28.  
  29.     return False
  30.  
  31.  
  32.  
  33. head = node(1)
  34. head.left = node(2)
  35. head.right = node(3)
  36. head.left.left = node(4)
  37. head.left.right = node(5)
  38. head.right.right = node(6)
  39. head.left.left.right = node(7)
  40. head.right.right.left = node(8)
  41. head.left.left.right.left = node(9)
  42. head.left.left.right.left.left = node(10)
  43. head.right.right.left.right = node(11)
  44.  
  45. print("All ancestors of node 10 are : ")
  46. ancestors(head, 10)
  47. print("\nAll ancestors of node 5 are : ")
  48. ancestors(head, 5)
  49. print("\nAll ancestors of node 8 are : ")
  50. ancestors(head, 8)
Add Comment
Please, Sign In to add comment