[编程题]二叉搜索树的第k个结点
二叉搜索树的第k个结点
http://www.nowcoder.com/questionTerminal/ef068f602dde4d28aab2b210e859150a
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
//二叉搜索树的中序遍历是有序的
import java.util.ArrayList;
public class Solution {
TreeNode KthNode(TreeNode pRoot, int k)
{
if(pRoot==null||k<=0){
return null;
}
ArrayList<TreeNode> arr=new ArrayList<TreeNode>();
inorder(pRoot,arr);
//当k大于数组的长度,返回为空
if(k>arr.size()){
return null;
}
return arr.get(k-1);
}
//中序遍历二叉树
ArrayList<TreeNode> inorder(TreeNode pRoot,ArrayList<TreeNode> list){
if(pRoot==null){
return null;
}
inorder(pRoot.left,list);
list.add(pRoot);
inorder(pRoot.right,list);
return list;
}
}