
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Kth Smallest Element in a BST in Python
Suppose we have a binary search tree. We have to find the Kth smallest element in that BST. So if the tree is like −
So if we want to find 3rd smallest element, then k = 3, and result will be 7.
To solve this, we will follow these steps −
- create one empty list called nodes
- call solve(root, nodes)
- return k – 1th element of nodes
- the solve method is created, this takes root and nodes array, this will work as follows −
- if root is null, then return
- solve(left of root, nodes)
- add value of root into the nodes array
- solve(right of root, nodes)
Let us see the following implementation to get better understanding −
Example
class TreeNode: def __init__(self, data, left = None, right = None): self.data = data self.left = left self.right = right def insert(temp,data): que = [] que.append(temp) while (len(que)): temp = que[0] que.pop(0) if (not temp.left): temp.left = TreeNode(data) break else: que.append(temp.left) if (not temp.right): temp.right = TreeNode(data) break else: que.append(temp.right) def make_tree(elements): Tree = TreeNode(elements[0]) for element in elements[1:]: insert(Tree, element) return Tree class Solution(object): def kthSmallest(self, root, k): nodes = [] self.solve(root,nodes) return nodes[k-1] def solve(self, root,nodes): if root == None: return self.solve(root.left,nodes) nodes.append(root.data) self.solve(root.right,nodes) ob1 = Solution() tree = make_tree([10,5,15,2,7,13]) print(ob1.kthSmallest(tree, 3))
Input
[10,5,15,2,7,13] 3
Output
7
- Related Articles
- Kth Smallest Element in a Sorted Matrix in Python
- Program to find kth smallest element in linear time in Python
- Find k-th smallest element in BST (Order Statistics in BST) in C++
- Program to find the kth smallest element in a Binary Search Tree in Python
- Kth smallest element after every insertion in C++
- Kth Largest Element in a Stream in Python
- Program to find kth smallest n length lexicographically smallest string in python
- Kth Largest Element in an Array in Python
- Python – Find Kth Even Element
- Kth Smallest Number in Multiplication Table in C++
- Filter Tuples by Kth element from List in Python
- kth smallest/largest in a small range unsorted array in C++
- Closest Pair to Kth index element in Tuple using Python
- Python – Extract Kth element of every Nth tuple in List
- Kth Largest Element in an Array

Advertisements