剑指offer01--二叉树的最近公共祖先

给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。

例如,给定如下二叉树: root = [3,5,1,6,2,0,8,null,null,7,4]
在这里插入图片描述
采用递归算法,如下

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    if(root==null || root==p || root==q)
        return root;
    
    TreeNode l=lowestCommonAncestor(root.left,p,q);
    TreeNode r=lowestCommonAncestor(root.right,p,q);

    if(l==null)
        return r;
    if(r==null)
        return l;

    return root;


    }
}

示例:输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 6, q = 4
(蓝色箭头代表孩子,橙色代码返回数值 n代表空)
在这里插入图片描述

发布了114 篇原创文章 · 获赞 32 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/moqianmoqian/article/details/104451788