一、题目描述
给定一棵二叉搜索树,请找出其中的第k小的结点。例如(5,3,7,2,4,6,8)中,按结点数值大小顺序第三小结点的值为4。
二、解题思路
二叉搜索树:左子结点的值 < 根结点的值 < 右子结点的值。
二叉搜索树中序遍历序列为递增序列,所以中序遍历到第k个结点即为第k小的结点。
三、编程实现
public class Solution {
int index = 0;
TreeNode KthNode(TreeNode pRoot, int k) {
// 中序遍历到第k个结点即为第k小的结点
if (pRoot != null) {
TreeNode node = KthNode(pRoot.left, k);
if (node != null) {
return node;
}
index++;
if (index == k) {
return pRoot;
}
node = KthNode(pRoot.right, k);
if (node != null) {
return node;
}
}
return null;
}
}