题解 | #二叉搜索树的第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;
        
    }
    


}
全部评论

相关推荐

不愿透露姓名的神秘牛友
07-09 11:30
找工作7个月,投了7000封,3段世界五百强实习,才有一个offer,牛油们肯定比我强吧
码农索隆:不对不对不对,实习经历这么厉害,简历也没少投,问题出在哪呢
点赞 评论 收藏
分享
06-28 22:48
已编辑
广东金融学院 Java
小浪_Coding:学院本+这俩项目不是buff叠满了嘛
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务