codeTop100题(19)236. 二叉树的最近公共祖先

78 阅读1分钟

1. 题目

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

2. 分析

  • 首先看到给出的TreeNode结构没有parent指针,所以我们需要从根节点开始遍历
  • 祖先节点的条件是什么呢?
    • 两个节点分别在当前节点的左右
    • 或者当前节点为两个节点其中一个
  • 我们可以通过递归的方式解决:
    • 如果root为空,直接返回null
    • 如果root正好等于p 或者 q,那么当前节点就是公共祖先
    • 递归调用left 找 p 和 q的公共祖先 与 right 找 p 和 q的公共祖先
    • 最终 left 和 right 哪个不为空,就是要找的公共祖先

3. 代码

public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    if (null == root) {
        return null;
    }
    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;
    }
    return null == left ? right : left;
}