JZ62-二叉搜索树的第k个结点
二叉搜索树的第k个结点
https://www.nowcoder.com/practice/ef068f602dde4d28aab2b210e859150a?tpId=13&tags=&title=&diffculty=0&judgeStatus=0&rp=1&tab=answerKey
class Solution2 {
TreeNode KthNode(TreeNode pRoot, int k) {
if (pRoot == null) {
return pRoot;
}
Stack<TreeNode> stack = new Stack<>();
stack.push(pRoot); //压入根
while (!stack.isEmpty()) {
if (pRoot.left != null) { //有左节点
stack.push(pRoot.left);
pRoot = pRoot.left; //*******************************************************
} else { //无左节点 必须加else
TreeNode temp = stack.pop(); //先弹出左->根节点
if (--k == 0) { //返回对应的数
return temp;
}
if (temp.right != null) {
stack.add(temp.right); //再压入右节点
pRoot = temp.right; //遍历右子树....左边是root
}
}
}
return null;
}
} 
查看1道真题和解析