From 0bf1f22d37b8732a2f8ec74e7eace0068a0c231f Mon Sep 17 00:00:00 2001 From: SiddhantBobde <58205856+SiddhantBobde@users.noreply.github.com> Date: Fri, 21 Aug 2020 12:25:50 +0530 Subject: [PATCH] Added function for finding K-th smallest element in BST (#2318) * fixes: #2172 * fixes: #2172 * Added docstrings and type of parameters * fixed error * Added type hints * made changes * removed capital letters from function name * Added type hints * fixed bulid error * modified comments * fixed build error --- data_structures/binary_tree/binary_search_tree.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/data_structures/binary_tree/binary_search_tree.py b/data_structures/binary_tree/binary_search_tree.py index 386813035..45c3933fe 100644 --- a/data_structures/binary_tree/binary_search_tree.py +++ b/data_structures/binary_tree/binary_search_tree.py @@ -141,6 +141,20 @@ class BinarySearchTree: else: return traversal_function(self.root) + def inorder(self, arr: list, node: Node): + """Perform an inorder traversal and append values of the nodes to + a list named arr""" + if node: + self.inorder(arr, node.left) + arr.append(node.value) + self.inorder(arr, node.right) + + def find_kth_smallest(self, k: int, node: Node) -> int: + """Return the kth smallest element in a binary search tree """ + arr = [] + self.inorder(arr, node) # append all values to list using inorder traversal + return arr[k - 1] + def postorder(curr_node): """