非递归中序遍历,arraylist存储,直接取第k-1个就ok。


import java.util.*;

/*
 * 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) {
        // write code here
        ArrayList<Integer>list=new ArrayList<>();
        if(proot==null||k<=0)return -1;
        Stack<TreeNode>stack=new Stack<>();
        while(proot!=null||!stack.isEmpty()){
            while(proot!=null){
                stack.push(proot);
                proot=proot.left;
            }
            proot=stack.pop();
            list.add(proot.val);
            proot=proot.right;
        }
     if(list.size()<k)return -1;
        return list.get(k-1);
    }
}