题解 | #二叉搜索树的最近公共祖先#

二叉搜索树的最近公共祖先

https://www.nowcoder.com/practice/d9820119321945f588ed6a26f0a6991f

记录一个错误:
由于Queue中存的是Integer类型,而Integer类型值在超过127之外就是不相同的(值相等但是对象不相同!),所以这里比较相等时一定要转化为int类型,不然就用equals,千万不要图省力把许多步合成一步!
    public int lowestCommonAncestor (TreeNode root, int p, int q) {
        // write code here
        
        Queue<Integer>queue1=new LinkedList<>();
        Queue<Integer>queue2=new LinkedList<>();
        TreeNode cur=root;
        while(cur.val!=p){
            queue1.offer(cur.val);
            if(cur.val>p)
                cur=cur.left;
            else if(cur.val<p)
                cur=cur.right;       
        }
        queue1.offer(cur.val);
        
        cur=root;
        while(cur.val!=q){
            queue2.offer(cur.val);
            if(cur.val>q)
                cur=cur.left;
            else if(cur.val<q)
                cur=cur.right;        
        }
        queue2.offer(cur.val);
        
        int par=0;
        for(int i:queue1)
            System.out.println(i);
        for(int i:queue2)
            System.out.println(i);    
        while(queue1.peek()==queue2.peek()){

            par=queue1.poll();
            System.out.println(par);    
            System.out.println(queue2.poll());

        }
        
        return par;
    }
}


全部评论

相关推荐

06-14 19:09
门头沟学院 Java
darius_:给制造业搞的,什么物料管理生产管理,设备管理点检,最最关键的就是一堆报表看板。个人觉得没啥技术含量都是些基本的crud,但是业务很繁琐那种
点赞 评论 收藏
分享
屌丝逆袭咸鱼计划:心态摆好,man,晚点找早点找到最后都是为了提升自己好进正职,努力提升自己才是最关键的😤难道说现在找不到找的太晚了就炸了可以鸡鸡了吗😤早实习晚实习不都是为了以后多积累,大四学长有的秋招进的也不妨碍有的春招进,人生就这样
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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