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.
Algorithm
Traverse the tree inorder, store the corresponding number, and return the kth number.
Code
# 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:
ans = []
def visit(root):
nonlocal ans
if root.left:
visit(root.left)
ans.append(root.val)
if root.right:
visit(root.right)
visit(root)
return ans[k-1]