递归 java 中序遍历
给定一个二叉搜索树,编写一个函数 kthSmallest 来查找其中第 k 个最小的元素。
说明:
你可以假设 k 总是有效的,1 ≤ k ≤ 二叉搜索树元素个数。
class Solution {
private int count=1;
private int res;
public int kthSmallest(TreeNode root, int k) {
inorder(root,k);
return res;
}
public void inorder(TreeNode root, int k){
if(root==null) return;
inorder(root.left,k);
if(count++==k){
res=root.val;
return;
}
inorder(root.right,k);
}
}