Skip to content

力扣链接:230.二叉搜索树中第k小的元素

难度:⭐⭐

解题关键词:二叉搜索树中序遍历

解题思路:使用中序遍历二叉搜索树,本身就是一个单调递增的值,然后用一个 flag 标识到了第几个,然后到了 k 个,直接返回节点的值就行了。

typescript
function kthSmallest(root: TreeNode | null, k: number): number {
  // 用一个栈来做中序遍历
  const stack: TreeNode[] = []
  // 标识到了第几个节点
  let no = 0

  while (stack.length || root !== null) {
    // 找到最左边的节点
    while (root !== null) {
      stack.push(root)
      root = root.left
    }
    root = stack.pop()

    // 如果到了第 k 个元素,直接返回
    if (++no === k) {
      return root.val
    }

    // 处理右节点
    root = root.right
  }
};