中序遍历 + 一个计数变量即可解决
class Solution:
def kthSmallest(self, root: TreeNode, k: int) -> int:
count = 0
res = float('inf')
def helper(root, k):
nonlocal count
nonlocal res
if not root:
return
helper(root.left, k)
count += 1
if count == k: #找到第k小的数
res = root.val
return
helper(root.right, k)
helper(root, k)
return res