给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。
思考:二叉搜索树的中序遍历是按顺序的,递归中序遍历,保存到动态数组里面,直接找第K个结点。
代码:
import java.util.ArrayList;
public class Solution {
TreeNode KthNode(TreeNode pRoot, int k)
{
if(pRoot==null||k<=0){
return null;
}
ArrayList list=new ArrayList();
zxbl(pRoot,list);
if(list.size()=0) {
return null;
}
if(k>list.size()) {
return null;
}
return list.get(k-1);
}
public static void zxbl(TreeNode pRoot,ArrayList list){
if(pRoot=null){
return ;
}
if(pRoot.left!=null){
zxbl( pRoot.left,list);
}
list.add( pRoot);
if(pRoot.right!=null){
zxbl( pRoot.right,list);
}
}
}