class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if root is None or root == p or root == q:
return root
l = self.lowestCommonAncestor(root.left, p, q)
r = self.lowestCommonAncestor(root.right, p, q)
if l and r:
return root
if l:
return l
if r:
return r
时间复杂度:O(h)
空间复杂度:O(h)
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if not root:
return
if root == p: # 根据自身节点的性质, 节点返回
return p
if root == q:
return q
l = self.lowestCommonAncestor(root.left, p, q)
r = self.lowestCommonAncestor(root.right, p, q)
if l and r: # 根据左右子树的结果, 节点返回
return root
if not l and r:
return r
if not r and l:
return l
迭代 iteration
import collections
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
queue = collections.deque([root])
parent = {root: None}
ancestors = set() # p's ancestors
while p not in parent or q not in parent:
root = queue.popleft()
if root.left:
parent[root.left] = root
queue.append(root.left)
if root.right:
parent[root.right] = root
queue.append(root.right)
while p:
ancestors.add(p)
p = parent[p]
while q not in ancestors:
q = parent[q]
return q
# 160. Intersection of Two Linked Lists
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
self.parent = None
class Solution(object):
def lowestCommonAncestor(self, p, q):
node_set = set()
while p:
node_set.add(p)
p = p.parent
while q not in node_set:
q = q.parent
return q
# O(1) space, 类似160的思路
class Solution(object):
def lowestCommonAncestor(self, p, q):
a = p
b = q
while a != b:
# If pointer_a has a parent, move to the parent; otherwise, go to the other node's initial position.
a = a.parent if a else q
b = b.parent if b else p
return a