public class Solution {
public int KthNode (TreeNode proot, int k) {
//为空返回-1
if (proot == null) {
return -1;
}
//计数
int count = 0;
//临时变量
TreeNode p = null;
//用栈辅助构建中序
Stack<TreeNode> ck = new Stack<>();
//判断
while(!ck.isEmpty() || proot != null){
//当proot不为空则一直循环
while(proot != null){
//把proot压入栈(proot是变量)
ck.push(proot);
//中序遍历,左中右
//先把左节点压入栈(已经包括根节点)
proot = proot.left;
}
//弹出栈的最后进入的节点
p = ck.pop();
count++;
//判断是不是第k个节点
if(count == k)
return p.val;
//跳出上边循环则说明左边的已经压入完毕,压入右边的
proot = p.right;
}
return -1;
}
}
03-05
348
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)