给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。
二叉搜索树中序遍历压扁就是有序数列,判断中序遍历第k个即可。
public class Solution {
int count = 0;
TreeNode ans = null;
public TreeNode KthNode(TreeNode pRoot, int k){
if(k <= 0) return null;
inorder(pRoot, k);
return ans;
}
public void inorder(TreeNode node, int k){
if(node == null) return;
inorder(node.left, k);
count++;
if(count == k){
ans = node;
return;
}
inorder(node.right, k);
}
}