classSolution:deflowestCommonAncestor(self, root:'TreeNode', p:'TreeNode', q:'TreeNode')->'TreeNode':
ancestor=root
whileTrue:if p.val<ancestor.val and q.val<ancestor.val:
ancestor=ancestor.left #如果p/q都小于根节点,在左子树找elif p.val>ancestor.val and q.val>ancestor.val:
ancestor=ancestor.right
else:breakreturn ancestor
二叉树的最近公共祖先
classSolution:deflowestCommonAncestor(self, root:'TreeNode', p:'TreeNode', q:'TreeNode')->'TreeNode':ifnot root or root==p or root==q:return root
left=self.lowestCommonAncestor(root.left,p,q)
right=self.lowestCommonAncestor(root.right,p,q)#动态递归ifnot left:return right
ifnot right:return left
return root