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

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

核心逻辑

本解法采用 递归 的策略:

  1. 递归终止条件
    • 如果 root == null,说明走到底了还没找到 p 和 q ,返回 null
    • 如果 root 就是 pq 其中一个,则直接返回 root
  2. 递归搜索
    • 分别在 root 的左子树 (left) 和右子树 (right) 中搜索 pq
  3. 合并结果
    • left 不为空且 right 不为空,说明 pq 分别位于 root 的两侧,因此 root 就是最近公共祖先,返回 root
    • 若只有 left 不为空,说明 pq 都在左子树中,返回 left
    • 若只有 right 不为空,说明 pq 都在右子树中,返回 right
    • leftright 都为空,说明该子树不包含 pq,返回 null

🔥代码实现

/**
 * 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) {
        // 终止条件 1:遍历到空节点
        if (root == null) {
            return null;
        }
        // 终止条件 2:当前节点就是目标节点 p 或 q(直接比较引用)
        if (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;
        } else if (left != null && right == null) {
            return left;
        } else if (right != null && left == null) {
            return right;
        } else {
            return null;
        }
    }
}

📚遇到的问题:

image-cDcD.png

这是最初思路。首先,原思路认为 leftright 在子树中绝对存在,递归时一定能找到,这一点没毛病。

但随后产生了一个错误想法:认为 leftright 不会为 null

由于叶子节点本身没有左右子节点,所以以叶子节点为基准时,leftright 就是真实的 null。而原代码在逻辑处理上直接 return root没有返回 null。这样一来,由底向上返回时,各个节点都会返回 root,最终直接返回了根节点,导致错误。