1 /**
2 * Definition for a binary tree node.
3 * struct TreeNode {
4 * int val;
5 * TreeNode *left;
6 * TreeNode *right;
7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8 * };
9 */
10 class Solution {
11 public:
12 TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
13 if(root==nullptr||p==nullptr||q==nullptr)
14 return nullptr;
15 if(root==p)
16 return root;
17 if(root==q)
18 return root;
19 TreeNode* left=lowestCommonAncestor(root->left,p,q);
20 TreeNode* right=lowestCommonAncestor(root->right,p,q);
21 if(left&&right)
22 return root;
23 return left?left:right;
24 }
25 };