-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproblem325.cpp
More file actions
27 lines (26 loc) · 744 Bytes
/
problem325.cpp
File metadata and controls
27 lines (26 loc) · 744 Bytes
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
/**
* 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* findAncestor(TreeNode* root, TreeNode* p, TreeNode* q){
TreeNode* store;
if(p->val > root->val && q->val > root->val){
store = findAncestor(root->right, p, q);
}else if(p->val < root->val && q->val < root->val){
store = findAncestor(root->left, p , q);
}else{
store = root;
}
return store;
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
return findAncestor(root, p, q);
}
};