Given the root of a binary search tree and an integer k, return the kth smallest element in the tree. A solution will always exist.
Example:
kthSmallestElementBST(TreeNode.of([1]), 1)
# 1kthSmallestElementBST(TreeNode.of([2, 1]), 1)
# 1kthSmallestElementBST(TreeNode.of([2, 1]), 2)
# 20. Problem
No matter where you are in the BST, all the left children will have a smaller value, and all the right children will have a greater value:
A useful trick is that inorder traversals visit the nodes in a BST from smallest to largest. This is because inorder traversals visit left subtree, then the current node, then the right subtree, L c R. So on a BST, they end up visiting all the "smaller" left nodes, then the current node, then all the "larger" right nodes.
This means to solve this problem, we can just do an inorder traversal and keep track of which element we're on. The kth element is the answer.
1. Recursion
We want to do an inorder traversal, keeping track which element we're on. When we get to the kth element, we want to set it as the solution.
solution = None
c = 1
def inorder(node):
nonlocal c, solution
inorder(node.left)
# set the kth element in traversal as the solution
if c == k:
solution = node.val
# increment count
c += 1
inorder(node.right)2. Base case
We stop traversing when there are no nodes left or if we already found a value:
if node == None or solution != None:
return # do nothing3. Code
Combining the recursion and base case gives:
def kthSmallestElementBST(root, k):
c = 1
solution = None
def inorder(node):
nonlocal c, solution
# base case
if node == None or solution != None:
return
# recursion
inorder(node.left)
if c == k:
solution = node.val
c += 1
inorder(node.right)
inorder(root) # sets solution
return solutionTime Complexity O(k). We iterate through k nodes in the traversal.
Space Complexity O(k). The variables c and found take up O(2) memory. The recursion goes to a depth of k, so the Call Stack grows to a height of O(k), and each call in the Call Stack uses O(1) memory. This is O(2) + O(k)*O(1) = O(k) total memory.