题目: 给定一个二叉搜索树,编写一个函数 kthSmallest 来查找其中第 k 个最小的元素。
说明: 你可以假设 k 总是有效的,1 ≤ k ≤ 二叉搜索树元素个数。
示例 1: 输入: root = [3,1,4,null,2], k = 1 3 / \ 1 4 \ 2 输出: 1 示例 2: 输入: root = [5,3,6,2,4,null,null,1], k = 3 5 / \ 3 6 / \ 2 4 / 1 输出: 3进阶: 如果二叉搜索树经常被修改(插入/删除操作)并且你需要频繁地查找第 k 小的值,你将如何优化 kthSmallest 函数? 题解: 二叉搜索树的中序遍历刚好是有序的。所以直接使用中序遍历即可。 java代码:
/** * 二叉搜索树的中序遍历刚好是有序的 * * @param root * @param k * @return */ public static int kthSmallest(TreeNode root, int k) { if (root == null) return 0; Stack<TreeNode> stack = new Stack<>(); int count = 0; int res = -1; while (!stack.isEmpty() || root != null) { if (root != null) { stack.push(root); root = root.left; } else { TreeNode pop = stack.pop(); count++; if (count == k) { res = pop.value; break; } root = pop.right; } } return res; }