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
22 changes: 22 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,28 @@ def traversal_tree(self, traversal_function=None):
else:
return traversal_function(self.root)

def inorder(self, arr, Node):
"""This function performs inorder traversal and append values of nodes to list named arr
Args:-
arr -> list
Node -> object of class Node
"""
if Node:
self.inorder(arr, Node.left)
arr.append(Node.value) # appends values of nodes to list arr
self.inorder(arr, Node.right)

def find_Kth_Smallest(self, k, Node):
""" Function return kth smallest element in BST
Args:-
k -> int
Node -> object of class Node
Returns:- int
"""
arr = []
self.inorder(arr, Node) # append all values to list using inorder traversal
return arr[k - 1] # returns the kth smallest element in BST


def postorder(curr_node):
"""
Expand Down