Python
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if root in [None, p, q]: return root
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
return root if left and right else left or right
两种情况
1.单边找到
a.已经p and q都找到,返回之前的答案
b.只找到一边,是需要update node但是可以在两边找到的时候完成
2.两边找到,当前node
C++
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(!root || root==p || root==q) return root;
TreeNode* l = lowestCommonAncestor(root->left, p, q);
if(l && l!=p && l!=q) return l;
TreeNode* r = lowestCommonAncestor(root->right, p, q);
if(r && r!=p && r!=q) return r;
if(l && r) return root;
return l?l:r;
}
};