採用分治法來求解:
如果找到任意一個node 則返回,這樣就可以分爲三種情況。兩個node 在左右子樹都找到,返回root.
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root == NULL || root == p || root == q) return root;
//divide
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
//conquer
if(left != NULL && right != NULL) return root;
if(left != NULL) return left;
else return right;
return NULL;
}
};