二叉树:19二叉树的最近公共祖先

19. 二叉树的最近公共祖先

本题的两种情况pq向上有共同祖先t,q直接是p的祖先

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {//人工智能生成代码
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    // 如果根节点为空,直接返回null
    if (root == null) {
        return null;
    }
    // 如果根节点等于p或q,直接返回根节点
    if (root == p || root == q) {
        return root;
    }
    // 递归左子树,查找p和q的最近公共祖先
    TreeNode left = lowestCommonAncestor(root.left, p, q);
    // 递归右子树,查找p和q的最近公共祖先
    TreeNode right = lowestCommonAncestor(root.right, p, q);
    // 如果左子树和右子树都不为空,说明p和q分别在左右子树中,根节点就是最近公共祖先
    if (left != null && right != null) {
        return root;
    }
    // 如果左子树不为空,右子树为空,说明p和q至少其一在左子树中,继续递归左子树
    if (left != null) {
        return left;
    }
    // 如果右子树不为空,左子树为空,说明p和q都在(至少其一才对)右子树中,继续递归右子树
    if (right != null) {
        return right;
    }
    // 如果左右子树都为空,说明p和q都不在树中,返回null
    return null;
    }
}
class Solution {//错误代码
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    //采用后序遍历,当返回的左右子树都不为空的时候,就证明找到了值
    if(root == null) return root;

    
    //有递归就有回溯,这里就有回溯的影子
    TreeNode left = lowestCommonAncestor(p.left, p, q);
    TreeNode right = lowestCommonAncestor(p.right, p, q);
    //当遇见left和right分别为pq则层层返回正确答案
    if((left.val == p.val && right.val == q.val) || (left.val == q.val && right.val == p.val)) return root;
    //遇见了一个成功的则返回成功的那个节点
    if(left.val == p.val || right.val == p.val) return p;
    if(right.val == q.val || left.val == q.val) return q;
    //排除掉正确的答案
    if(left != null) return left;
    if(right != null) return right;
    //两个都不是自然返回null
    return null;
    }
}
class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    //采用后序遍历,当返回的左右子树都不为空的时候,就证明找到了值
    //终止条件null、遇到pq
    if(root == null) return root;
    //如果遇到了p或者遇到了q就向上返回
    if(root == p || root == q) return root;//遇到pq就可以直接返回了,情况二在这里就直接包含了
    
    //有递归就有回溯,这里就有回溯的影子
    TreeNode left = lowestCommonAncestor(root.left, p, q);
    TreeNode right = lowestCommonAncestor(root.right, p, q);

    //当遇见left和right都不为空则层层返回正确答案
    if(left != null && right != null) return root;

    //遇见了一个不为空的那就把那个层层返回
    if(left == null && right != null) return right;
    else if(left != null && right == null) return left;
    else return null;//左右都为空
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

曦煜墨白

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值