-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlt78.cpp
33 lines (32 loc) · 815 Bytes
/
lt78.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
* 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* func(TreeNode* root , TreeNode* p ,TreeNode* q){
if(root==NULL){
return nullptr;
}
if(root->val==p->val || root->val==q->val){
return root;
}
TreeNode* left= func(root->left,p,q);
TreeNode* right = func(root->right,p,q);
if(left!= nullptr && right!=nullptr){
return root;
}
if(left==NULL){
return right;
}
return left;
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
return func(root,p,q);
}
};