LeetCode236找二叉树最近公共祖先,不知道哪里出问题了,思路应该是对的吧

来源:7-7 二分搜索树中的问题 Lowest Common Ancestor of a Binary Search Tree

不考过程序员不改名字

2022-03-22

    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root==null||p==null||q==null){
            return null;
        }
        //p在左子树
        boolean pInLeft = existNode(root.left,p.val);
        //q在左子树
        boolean qInLeft = existNode(root.left,q.val);
        //p在右子树
        boolean pInRight = !pInLeft;
        //q在右子树
        boolean qInRight = !qInLeft;
        if (pInLeft&&qInLeft){
            return lowestCommonAncestor(root.left,p,q);
        }else if (pInRight&&qInRight){
            return lowestCommonAncestor(root.right,p,q);
        }else {
            return root;
        }
    }
    public boolean existNode(TreeNode root,int target){
        if (root==null){
            return false;
        }
        if (root.val == target){
            return true;
        }
        return existNode(root.left,target)||existNode(root.right,target);
    }

思路就是判断p,q节点分别存在的位置做判断,但是有个用例报错了不知道是哪里的问题,您能帮忙看下嘛

写回答

1回答

liuyubobobo

2022-03-22

如果 pInLeft 是 false, pInRight 就是 true。那么此时, pInRight 为 true 的情况下,不代表 p 一定在右子树,如果 p 就是 root 本身,pInRight 也为 true。


qInRight 同理。


所以在你的这个逻辑下,pInRight 和 qInRight 都是 true 的时候,公共祖先不一定在 root.right,有可能就是 root 本身。


继续加油!:)

1
1
不考过程序员不改名字
好的谢谢老师,刚看了下官方题解,直接寻找两个节点是否存在思路很清晰,已经明白啦!
2022-03-25
共1条回复

玩转算法面试-- Leetcode真题分门别类讲解

课程配套大量BAT面试真题,高频算法题解析,强化训练

7465 学习 · 1159 问题

查看课程