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).”
Idea
题为找到两个node的公共祖先。而且这两个给定的node p和q在tree中一定存在且tree里的任意node都是unique value的。
我们可以把题目分为以下几种情况:
- p和q有一个等于root:LCA为root
- p和q分别在左右子树中:LCA为root
- p和q同在左子树中:去左子树继续找LCA
- p和q同在右子树中:去右子树继续找LCA
in general,我们可以分别去左右子树找p和q并return第一个遇到的node。如果p和q在同一侧则第一个遇到的node为LCA, 如果不在同一侧 - 左右子树均能找到第一个遇到的node,则root 为LCA。
Code
下面展示一些 内联代码片
。
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if not root:
return None
# 第一种情况, p和q中有一个是root则root为公共祖先
if root == p or root == q:
return root
# 分别去左右子树寻找p和q, 并return找到的第一个node
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
# 如果left和right都能找到一个node,则root为LCA
if left and right:
return root
# 如果left或者right只有一个return了值那么那个return的值即为LCA
if left:
return left
return right
Notes
通过设计LCA函数为return第一个遇到的node,简化了代码:使同一段代码即可以找到LCA也可以判断p q是否在同一侧。