[LeetCode] 236. Lowest Common Ancestor of a Binary Tree(二叉树的最近公共祖先)

Description

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
给定一棵二叉树,找到给定两个节点的最近公共祖先。

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”
根据维基百科的定义:“最近公共祖先是节点 p 和 q,存在这样的一个 T 节点,同时是 p 和 q 的祖先,当这个祖先最靠近 p 和 q 时,为最近公共祖先。(一个节点的祖先可以是其本身)”

Examples

Example 1

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
Output: 3
Explanation: The LCA of nodes 5 and 1 is 3.

Example 2

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
Output: 5
Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.

Example 3

Input: root = [1,2], p = 1, q = 2
Output: 1

Constraints

  • The number of nodes in the tree is in the range [2, 105].
  • -109 <= Node.val <= 109
  • All Node.val are unique.
  • p != q
  • p and q will exist in the tree.

Solution

以下解答参考自本人的一本算法书

进行后序遍历,先行获得左右两个子树的查找结果:

  1. 左右查找的结果都是 null,说明找不到祖先,返回 null

  2. 左右查找的结果均非 null,说明左边找到了 pq (的祖先),右边也找到了 pq 的祖先,那么 root 即为其最近公共祖先

  3. 左右查找的结果有一个非 null,说明 pq 的最近公共祖先在 root 之前就找到了,返回这个非空的查找结果

递归的出口条件是:

  1. rootnull,这点不用多说

  2. root 为 p 或 q 的其中一个(题目规定了节点本身是自己的祖先)

代码如下:

/**
 * Definition for a binary tree node.
 * class TreeNode(var `val`: Int = 0) {
 *     var left: TreeNode? = null
 *     var right: TreeNode? = null
 * }
 */

class Solution {
    fun lowestCommonAncestor(root: TreeNode?, p: TreeNode?, q: TreeNode?): TreeNode? {
        if (root == null || root.`val` == p?.`val` || root.`val` == q?.`val` ) {
            return root
        }
        val leftResult = lowestCommonAncestor(root.left, p, q)
        val rightResult = lowestCommonAncestor(root.right, p, q)

        if (leftResult == null && rightResult == null) {
            return null
        }
        if (leftResult != null && rightResult != null) {
            return root
        }

        return leftResult ?: rightResult
    }
}
原文地址:https://www.cnblogs.com/zhongju/p/14019178.html