题目描述
给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。
思路分析
用二叉搜索树的特性,中序遍历为升序有序数列做。用中序遍历一遍树,当到第K个结点时停止。
代码实现
private TreeNode resNode;
private int count=0;
TreeNode KthNode(TreeNode pRoot, int k)
{
inOrder(pRoot,k);
return resNode;
}
public void inOrder(TreeNode node,int k){
if(node==null || count>=k){
return;
}
inOrder(node.left,k);
if(++count==k){
resNode = node;
}
inOrder(node.right,k);
}