七七老师の白日梦
首页项目归档照片墙音乐灵境说说杂谈友链关于
封面

二叉树的最近公共祖先:情况思考

写作时间:2026-08-15 08:18:41

题目

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

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

思考

这道题无非四种情况

  1. 全空,没有,不必判断

  2. 一空,肯定在非空那边

  3. 无空,当前节点为要找的

  4. 节点为p或者q,当前节点上报找祖先

代码

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

//        根节点为p或者q
        if (root == p || root == q) {
            return root;
        }

//        后续遍历
        TreeNode right = lowestCommonAncestor(root.right, p, q);
        TreeNode left = lowestCommonAncestor(root.left, p, q);

//        找到两个
        if (right != null && left != null) {
            return root;
        }

        //        找到一个
//        注释这段和下面的三目运算符一样的作用
//        if (right != null && left == null) {
//            return root.right;
//        } else if(right == null && left != null) {
//            return root.left;
//        }
        return (left != null) ? left : right;
    }
}

‍

avatar

七七老师

分享代码日常

RECOMMENDED

七七旧事:复盘并改变写博客的方式

2026-07-02 22:54:38

字母异位词

2026-07-04 22:22:08

寻找两个正序数组的中位数:合并与二分

2026-07-08 15:56:26

Table of Contents