236. Lowest Common Ancestor of a Binary Tree

给定一棵二叉树,寻找其中两个给定节点的最近公共祖先(LCA)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
# 6 star, no idea
# 递归解决,向左右子树递归查找,直到找到p或q, 此时left和right的值有两种情况,一种是一个是lca一个是None, 另一种是分别是p和q
# 这个代码太简洁了,还得好好消化
if not root or root in (p, q):
return root
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
if left and right:
return root
return left or right