方法一:递归
/**
* 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) {
//递归结束条件,找到p、q,或者都没找到
if(!root || root==p || root==q)
return root;
TreeNode* l=lowestCommonAncestor(root->left,p,q); //左子树查找结果
TreeNode* r=lowestCommonAncestor(root->right,p,q); //右子树查找结果
//返回结果:
//如果左右都不为空,则root为公共祖先
//如果左右子树只有一个为空,则不为空的结果为公共祖先
//因为题目中指定是数中结点,不存在都查不到
return l==NULL?r:(r==NULL?l:root);
}
};