[LeetCode] 236. Lowest Common Ancestor of a Binary Tree(二叉树的最近公共祖先)
-
Difficulty: Medium
-
Related Topics: Tree
-
Link: https://leetcode.com/problems/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
andq
will exist in the tree.
Solution
以下解答参考自本人的一本算法书
进行后序遍历,先行获得左右两个子树的查找结果:
-
左右查找的结果都是
null
,说明找不到祖先,返回null
-
左右查找的结果均非
null
,说明左边找到了p
或q
(的祖先),右边也找到了p
或q
的祖先,那么root
即为其最近公共祖先 -
左右查找的结果有一个非
null
,说明p
和q
的最近公共祖先在root
之前就找到了,返回这个非空的查找结果
递归的出口条件是:
-
root
为null
,这点不用多说 -
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
}
}