leetcode 求二叉树的最近公共祖先(带图解)

题目描述

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

百度百科中最近公共祖先的定义为:“对于有根树 T 的两个节点 p、q,最近公共祖先表示为一个节点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”

解题思路

这里我们使用上述的树,假设我们输入的节点为 7,4:

    1.lowestCommonAncestor(3,7,4),(left为2,right为null)返回的就是left ->2 - 1.左 lowestCommonAncestor(5,7,4),(left 为空,right为2)返回2 1.左lowestCommonAncestor(6,7,4),(left 为空,right也为空)返回null 1.左lowestCommonAncestor(null,7,4),返回null,到上一层 2.右lowestCommonAncestor(null,7,4),返回null,到上一层 2.右lowestCommonAncestor(2,7,4),(left,right都不能为空)返回2 1.左lowestCommonAncestor(7,7,4),返回7 2.右lowestCommonAncestor(4,7,4),返回4 2.右lowestCommonAncestor(1,7,4),(left right都为null),返回null 1.左lowestCommonAncestor(0,7,4),(left right都为null),返回null 1.左lowestCommonAncestor(null,7,4),返回null 2.右lowestCommonAncestor(null,7,4),返回null 2.右lowestCommonAncestor(8,7,4),(left right都为null),返回null 1.左lowestCommonAncestor(null,7,4),返回null 2.右lowestCommonAncestor(null,7,4),返回null

由上述我们递归的一边可知,只有当节点为空,或者节点等于p,q 时才会返回,不然就会一直往下递归

代码展示

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

        TreeNode left = lowestCommonAncestor(root.left,p,q);
        TreeNode right= lowestCommonAncestor(root.right,p,q);
        if(left == null){
          
   
            return right;
        }
        if(right == null){
          
   
            return left;
        }
        return root;
    }
}
经验分享 程序员 微信小程序 职场和发展