From 038c94ba645c141306e038f494d4e0438b16a86d Mon Sep 17 00:00:00 2001 From: Charudatta Potdar Date: Mon, 19 Jun 2023 20:59:46 +0530 Subject: [PATCH] Implemented find_parent method in Binary Search Tree --- algorithms/Python/trees/binary_search_tree.py | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/algorithms/Python/trees/binary_search_tree.py b/algorithms/Python/trees/binary_search_tree.py index 41232ab6..ddca4bdf 100644 --- a/algorithms/Python/trees/binary_search_tree.py +++ b/algorithms/Python/trees/binary_search_tree.py @@ -201,6 +201,24 @@ class Node: if self.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): """ constructor """ @@ -234,6 +252,9 @@ if __name__ == '__main__': list_tree.delete(20) print("Deleted element: ", list_tree.in_order_traversal()) + parent = list_tree.find_parent(7) + print("Parent of 7 is ",parent.data) + # String BST country = ["India", "Australia", "France", "Japan", "Sweden"] country_tree = build_tree(country)