题解 | #二叉搜索树的第k个结点#
二叉搜索树的第k个结点
http://www.nowcoder.com/practice/ef068f602dde4d28aab2b210e859150a
利用栈进行中序遍历
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
import java.util.*;
public class Solution {
TreeNode KthNode(TreeNode pRoot, int k) {
if(pRoot == null || k==0){
return null;
}
Stack<TreeNode> we = new Stack<>();
while(true){
if(pRoot!=null){
we.push(pRoot);
pRoot=pRoot.left;
}else{
pRoot = we.pop();
System.out.print(pRoot.val);
if(--k == 0){
return pRoot;
}
pRoot = pRoot.right;
}
if(we.isEmpty() && pRoot == null){
// System.out.print(k);
break;
}
}
return null;
}
}