Skip to content

Added function for finding K-th smallest element in BST #2318

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 12 commits into from
Aug 21, 2020
14 changes: 14 additions & 0 deletions data_structures/binary_tree/binary_search_tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,20 @@ def traversal_tree(self, traversal_function=None):
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):
"""
Expand Down