题解 | #二叉搜索树的第k个节点#
二叉搜索树的第k个节点
http://www.nowcoder.com/practice/57aa0bab91884a10b5136ca2c087f8ff
非递归中序遍历,用一个计数器代表K,找到第K个就break
import java.util.*;
public class Solution {
public int KthNode (TreeNode proot, int k) {
// write code here
if(proot == null){
return -1;
}
Stack<TreeNode> s = new Stack<>();
int n = 0;
int res = -1;
while(!s.isEmpty() || proot != null){
if(proot != null){
s.push(proot);
proot = proot.left;
} else {
proot = s.pop();
if(++n == k){
res = proot.val;
break;
}
proot = proot.right;
}
}
return res;
}
}