Skip to content

Commit 0bf1f22

Browse files
Added function for finding K-th smallest element in BST (TheAlgorithms#2318)
* fixes: TheAlgorithms#2172 * fixes: TheAlgorithms#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
1 parent 0591968 commit 0bf1f22

File tree

1 file changed

+14
-0
lines changed

1 file changed

+14
-0
lines changed

data_structures/binary_tree/binary_search_tree.py

+14
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,20 @@ def traversal_tree(self, traversal_function=None):
141141
else:
142142
return traversal_function(self.root)
143143

144+
def inorder(self, arr: list, node: Node):
145+
"""Perform an inorder traversal and append values of the nodes to
146+
a list named arr"""
147+
if node:
148+
self.inorder(arr, node.left)
149+
arr.append(node.value)
150+
self.inorder(arr, node.right)
151+
152+
def find_kth_smallest(self, k: int, node: Node) -> int:
153+
"""Return the kth smallest element in a binary search tree """
154+
arr = []
155+
self.inorder(arr, node) # append all values to list using inorder traversal
156+
return arr[k - 1]
157+
144158

145159
def postorder(curr_node):
146160
"""

0 commit comments

Comments
 (0)