版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ccnuacmhdu/article/details/84926927
时间限制:1秒 空间限制:32768K 热度指数:143469
题目描述
给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
private int cnt = 0;
TreeNode KthNode(TreeNode pRoot, int k)
{
//如果这棵树本身就是空的,就不用再找了。。
if(pRoot == null){
return null;
}
//二叉树中序遍历的第k个节点
TreeNode node = KthNode(pRoot.left, k);//从左子树找到第k个节点
if(node != null){
return node;
}
//左子树如果没找到第k个节点,看根是不是
if(++cnt == k){
return pRoot;
}
//如果左子树没找到,根也不是,看右子树能不能找到
node = KthNode(pRoot.right, k);
if(node != null){
return node;
}
//如果左子树没找到,根也不是,右子树也没找到,那就找不到了。。。
return null;
}
}