MediumNo. 0230
Kth Smallest Element in a BST — LeetCode 230 Python Solution
- Pattern
- Tree Traversal
- Topics
- Tree, Depth-First Search, Binary Search Tree, Binary Tree
- On study lists
- Blind 75, NeetCode 150, Grind 75 and Top Interview 150
- Reading time
- 3 min
- Source
- leetcode.com
The problem
Given the root of a binary search tree, and an integer k, return the kth smallest value (1-indexed) of all the values of the nodes in the tree.
Example
- Input
- root = [3,1,4,null,2], k = 1
- Output
- 1
Python solution
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
stk = []
while root or stk:
if root:
stk.append(root)
root = root.left
else:
root = stk.pop()
k -= 1
if k == 0:
return root.val
root = root.rightComplexity
- Time
- O(V+E)
- Space · auxiliary
- O(V)
Pattern: Tree Traversal
Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 230. Kth Smallest Element in a BST is filed here because LeetCode tags it Tree, Binary Tree and Binary Search Tree, which is the vocabulary this hub collects.
The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0235 | Lowest Common Ancestor of a Binary Search Tree | Medium |
| 0098 | Validate Binary Search Tree | Medium |
| 0099 | Recover Binary Search Tree | Medium |
| 0449 | Serialize and Deserialize BST | Medium |
| 0501 | Find Mode in Binary Search Tree | Easy |
| 0530 | Minimum Absolute Difference in BST | Easy |
Frequently asked questions
- How hard is LeetCode 230. Kth Smallest Element in a BST?
LeetCode 230. Kth Smallest Element in a BST is rated Medium on LeetCode.
- What is the time complexity of LeetCode 230. Kth Smallest Element in a BST?
The Python solution on this page runs in O(V+E).
- What is the space complexity of LeetCode 230. Kth Smallest Element in a BST?
The Python solution on this page uses O(V) auxiliary space.
- What topics does LeetCode 230. Kth Smallest Element in a BST cover?
LeetCode 230. Kth Smallest Element in a BST is tagged Tree, Depth-First Search, Binary Search Tree and Binary Tree on LeetCode.