Note:
1、如果p q 分别在左右两个子树里,那么当前节点就是公共祖先
2、如果p q都在左子树,递归到左子树去找
3、如果p q都在右子树,递归到右子树去找
代码如下:
/**
* 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(p -> val > q -> val) swap(p, q);
//等号 如果两个指针指到根节点了,也是符合要求的
if(p -> val <= root -> val && q -> val >= root -> val) return root;
else if(q -> val < root -> val) return lowestCommonAncestor(root -> left, p, q);
else return lowestCommonAncestor(root -> right, p, q);
}
};