美文网首页
剑指 Offer 第68-2题: 二叉树的最近公共祖先

剑指 Offer 第68-2题: 二叉树的最近公共祖先

作者: 放开那个BUG | 来源:发表于2022-08-12 16:35 被阅读0次

1、前言

题目描述

2、思路

父节点可能在左边、右边、或者共同的父。

3、代码

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null || root == p || root == q){
            return root;
        }

        TreeNode left = lowestCommonAncestor(root.left, p, q);
        TreeNode right = lowestCommonAncestor(root.right, p, q);

        if(left != null && right != null){
            return root;
        }
        
        return left == null ? right : left;
    }
}

相关文章

网友评论

      本文标题:剑指 Offer 第68-2题: 二叉树的最近公共祖先

      本文链接:https://www.haomeiwen.com/subject/kxobbrtx.html