二叉搜索树的第K个节点(利用中序遍历的思想,把遍历结果先存入list集合中,然后通过list的get方法进行取值)
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* public TreeNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param proot TreeNode类
* @param k int整型
* @return int整型
*/
public int KthNode (TreeNode proot, int k) {
//判断proot结点是否为空,k是否小于等于0
if(proot==null || k<=0){
return -1;
}
//list集合用来存储二叉排序树中序遍历的结果
ArrayList<Integer> list=new ArrayList<Integer>();
//中序遍历(递归的方式)
infixOrder(proot,list);
//判断k的值是否大于集合中元素的个数
if(k>list.size()){
return -1;
}
//返回集合中第k个元素
return list.get(k-1);
}
//中序遍历
public void infixOrder(TreeNode proot,ArrayList<Integer> branchList){
//先左子树
if(proot.left!=null){
this.infixOrder(proot.left,branchList);
}
//再根结点
branchList.add(proot.val);
//再右子树
if(proot.right!=null){
this.infixOrder(proot.right,branchList);
}
}
}