递归,考虑4种情况。
- pq不在左右子树,返回NULL
- pq同时在左子树,返回left
- pq同时在右子树,返回right
- pq分别在左右子树,返回root,即为所求
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(!root || root==p || root==q) return root;
TreeNode* left=lowestCommonAncestor(root->left,p,q);
TreeNode* right=lowestCommonAncestor(root->right,p,q);
if(!left && !right) return NULL;
else if(left && !right) return left;
else if(!left && right) return right;
return root;
}
};