利用二叉搜索树的特点,左边节点的值<中间节点的值<右边节点的值,对二叉树进行中序遍历即可。通过res
保存值,count
记录遍历了多少个。中序遍历是在中间输出节点,所以count在中间++
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* @param proot TreeNode类
* @param k int整型
* @return int整型
*/
public int res = -1;
public int count = 0;
public void fun(TreeNode proot, int k) {
// write code here
if (proot != null && res == -1) {
KthNode(proot.left, k);
count++;
if (count == k)
res = proot.val;
KthNode(proot.right, k);
}
}
public int KthNode(TreeNode proot, int k) {
fun(proot, k);
return res;
}
}