思路:
若根节点为空或者根节点等于p或者q,则最近公共祖先就是root;
分开递归查找,left记录左子树查找的情况;right记录右子树查找的情况。
- 若left不为空,right为空,说明p、q都在左子树中,返回left;
- 若left为空,right不为空,说明p、q都在右子树中,返回right;
- 若left、right都不为空,说明p、q分布在左右子树中,返回root。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def lowestCommonAncestor(self, root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode:
#若根节点为空或者根节点等于p和q,则返回root:
if not root or root==p or root==q:
return root
else:
left=self.lowestCommonAncestor(root.left,p,q)
right=self.lowestCommonAncestor(root.right,p,q)
if left and right:
return root
else:
return left if left else right