递归 (分岔点即公共祖先):
l、r 非空时,说明 p、q 分居 root 的两侧,root 就是 最近公共祖先
l、r 任一为空,说明 最近公共祖先位于另一子树或其祖先中
c++
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(!root || root==p || root==q){ // 递归终止条件,当前节点是target或节点是空的
return root;
}
// 判断root不是目标任何一个情况后,分别搜索左右子树
TreeNode* l = lowestCommonAncestor(root->left, p, q);
TreeNode* r = lowestCommonAncestor(root->right, p, q);
// 已排除root是q或p, q,p只能在子树
// l空,则q,p在右子树, 返回右节点继续递归
// l非空且r非空,则q,p分别在左右树,当前遍历节点就是分岔点,即公共祖先,返回root
// l非空且r空,则q,p分别在左树, 返回左节点继续递归
return l? (r? root:l):r;
}
};
python
class Solution:
def lowestCommonAncestor(self, root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode:
if not root or root == q or root == p:
return root
# 已判断完root不是p或q
l = self.lowestCommonAncestor(root.left, p, q) # 调用本Class中一级def,用 self.函数名
r = self.lowestCommonAncestor(root.right, p, q)
return root if l and r else l or r