题解 | #二叉搜索树的第k个节点#
二叉搜索树的第k个节点
http://www.nowcoder.com/practice/57aa0bab91884a10b5136ca2c087f8ff
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
// 一些特殊情况的处理
if (null == proot || 0 == k) {
return -1;
}
Stack<TreeNode> stack = new Stack<>();
TreeNode tmpNode = proot;
int p = 0; // 记录当前是第几个节点
int rs = Integer.MAX_VALUE;
while (null != tmpNode) {
stack.push(tmpNode);
tmpNode = tmpNode.left;
}
while (!stack.isEmpty()) {
tmpNode = stack.pop();
p++;
if (p == k) {
rs = tmpNode.val;
break;
}
if (null != tmpNode.right) {
tmpNode = tmpNode.right;
while (null != tmpNode) {
stack.push(tmpNode);
tmpNode = tmpNode.left;
}
}
}
return rs == Integer.MAX_VALUE ? -1 : rs;
}
}