BINARY TREE

二叉搜索树中第 K 小的元素

中等#230时间 O(h+k)空间 O(h)力扣原题 ↗

题目

在二叉搜索树中寻找第 k 小的节点值,k 从 1 开始。演示要求输入为有效搜索树。

示例输入root = [3,1,4,null,2], k = 1
示例输出1

思路

搜索树的中序遍历严格递增。用显式栈模拟递归,沿左边压栈,弹出时记录一个值,数到 k 就返回。

每一步都成立

已弹出的节点是递增序列的前缀;栈顶是下一次回溯的位置。

看它一步步执行

用的是题目示例
数组 / nums步骤 1
执行状态
这次的结果播放到最后查看

Solution.java参考解法 · 高亮的是正在执行的行
1class Solution {2    public int kthSmallest(TreeNode root, int k) {3        Deque<TreeNode> stack = new ArrayDeque<>();4        TreeNode current = root;5        while (current != null || !stack.isEmpty()) {6            while (current != null) {7                stack.push(current);8                current = current.left;9            }10            current = stack.pop();11            if (--k == 0) return current.val;12            current = current.right;13        }14        throw new IllegalArgumentException("k 超出节点数");15    }16}
← → 单步 · 空格 播放
↑↓ 选择↵ 打开Pagefind 全文检索