算法1
递归
从在root树里面找 p
和q
的公共祖先;
递归:
p
和q
都不是root, 直接在子树里面递归:
否则额外考虑下p
和q
是root的情况。
C++ 代码
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (!root) return root;
if (root == p || root == q) {
return root;
}
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
if (left == NULL || right == NULL) {
return left == NULL ? right : left;
}
return root;
}
};
TreeNode* right = lowestCommonAncestor(root->right, p, q);
奥,对~