Implemented find_parent method in Binary Search Tree

pull/1202/head
Charudatta Potdar 2023-06-19 20:59:46 +05:30
parent d3c2184af8
commit 038c94ba64
1 changed files with 21 additions and 0 deletions

View File

@ -201,6 +201,24 @@ class Node:
if self.right: if self.right:
self.right.display() # display tree(right) self.right.display() # display tree(right)
def find_parent(self, data):
# Find the parent node of given node
parent = self
if data < self.data:
if data == self.left.data:
return parent
else:
return self.left.find_parent(data)
elif data > self.data:
if data == self.right.data:
return parent
else:
return self.right.find_parent(data)
return "Root node data"
def build_tree(elements): def build_tree(elements):
""" constructor """ """ constructor """
@ -234,6 +252,9 @@ if __name__ == '__main__':
list_tree.delete(20) list_tree.delete(20)
print("Deleted element: ", list_tree.in_order_traversal()) print("Deleted element: ", list_tree.in_order_traversal())
parent = list_tree.find_parent(7)
print("Parent of 7 is ",parent.data)
# String BST # String BST
country = ["India", "Australia", "France", "Japan", "Sweden"] country = ["India", "Australia", "France", "Japan", "Sweden"]
country_tree = build_tree(country) country_tree = build_tree(country)