题目描述
给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。
二叉搜索树的特点
二叉搜索树的特点:对于树中的每个节点X,它的左子树中所有关键字值小于X的关键字值,而它的右子树中所有关键字值大于X的关键字值。
根据这个性质,对一个二叉树进行中序遍历,如果是单调递增的,则可以说明这个树是二叉搜索树。
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
int index = 0;//计数器;
//必须得利用result节点 因为递归不断return 得有最终的一个变量保存最终结果
TreeNode result = null;
//思路:二叉搜索树按照中序遍历的顺序打印出来正好就是排序好的顺序。
//所以,按照中序遍历顺序找到第k个结点就是结果。
TreeNode KthNode(TreeNode pRoot, int k)
{
if(pRoot == null){
return pRoot;
}else{
KthNode(pRoot.left, k);
index++;
if(index == k){
result = pRoot;
}
KthNode(pRoot.right, k);
}
return result;
}
}