Kth Smallest Element in a BST
给定一个二叉搜索树,编写一个函数kthSmallest来查找其中第 k 个最小的元素。
说明:
你可以假设 k 总是有效的,1 ≤ k ≤ 二叉搜索树元素个数。
示例 1:
输入: root = [3,1,4,null,2], k = 1
输出: 1
示例 2:
输入: root = [5,3,6,2,4,null,null,1], k = 3
输出: 3
分析
由于是二叉搜索树,左子树的所有节点<根节点<右子树的所有节点(没有重复节点),因此我们可以采取中序遍历,先深入到最“左”节点,其必然是最小的元素,之后层层回溯,记录当前节点是倒数第几小的就可以了。
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private int index,res;
public int kthSmallest(TreeNode root, int k) {
if(root.left!=null) kthSmallest(root.left,k);
if(++index ==k) res = root.val;
if(root.right!=null) kthSmallest(root.right,k);
return res;
}
}