classSolution:deflowestCommonAncestor(self,root:'TreeNode',p:'TreeNode',q:'TreeNode') ->'TreeNode':if root isNoneor 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 rootif l:return lif r:return r
时间复杂度:O(h) 空间复杂度:O(h)
classSolution:deflowestCommonAncestor(self,root:'TreeNode',p:'TreeNode',q:'TreeNode') ->'TreeNode':ifnot root:returnif root == p:# 根据自身节点的性质, 节点返回return pif root == q:return q l = self.lowestCommonAncestor(root.left, p, q) r = self.lowestCommonAncestor(root.right, p, q)if l and r:# 根据左右子树的结果, 节点返回return rootifnot l and r:return rifnot r and l:return l
# 160. Intersection of Two Linked ListsclassNode:def__init__(self,val): self.val = val self.left =None self.right =None self.parent =NoneclassSolution(object):deflowestCommonAncestor(self,p,q): node_set =set()while p: node_set.add(p) p = p.parentwhile q notin node_set: q = q.parentreturn q
# O(1) space, 类似160的思路classSolution(object):deflowestCommonAncestor(self,p,q): a = p b = qwhile 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 preturn a