题解 | #二叉搜索树的第k个节点#
二叉搜索树的第k个节点
https://www.nowcoder.com/practice/57aa0bab91884a10b5136ca2c087f8ff
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* public TreeNode(int val) {
* this.val = val;
* }
* }
*/
//难在要考虑的情况太多了,后面真的面向示例编程....
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param proot TreeNode类
* @param k int整型
* @return int整型
*/
//记录返回的节点
TreeNode res = null;
//记录遍历了多少个
int count = 0;
void midOrder(TreeNode proof,int k){
//当前节点为null,或遍历节点数大于k时退出
if(proof==null || count>k){
return;
}
midOrder(proof.left,k);
count++;
if(count == k){
res = proof;
}
midOrder(proof.right,k);
}
public int KthNode (TreeNode proot, int k) {
// write code here
midOrder(proot,k);
if(res!=null){
return res.val;
}
return -1;
}
}

