题目
给定一棵二叉搜索树,请找出其中的第k小的结点。例如,(5,3,7,2,4,6,8)中,按结点数值大小顺序第三小结点的值为4。
思路
- 二叉搜索树的中序遍历结果为数值的递增排序。
- 中序遍历:左子树的中序遍历 --> 访问根节点 --> 右子树的中序遍历
private int curIndex = 0;
private TreeNode result;
private boolean isFinished = false;
TreeNode KthNode(TreeNode pRoot, int k)
{
inOrder(pRoot, k);
return result;
}
private void inOrder(TreeNode pRoot, int k) {
if (pRoot == null || isFinished) {
return;
}
inOrder(pRoot.left, k);
curIndex++;
if (curIndex == k) {
result = pRoot;
isFinished = true;
}
inOrder(pRoot.right, k);
}