-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path68-2.cpp
More file actions
41 lines (40 loc) · 962 Bytes
/
68-2.cpp
File metadata and controls
41 lines (40 loc) · 962 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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/**
* 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
{
private:
stack<TreeNode *> s1, s2;
bool getPath(TreeNode *root, TreeNode *p, stack<TreeNode *> &s)
{
if (root == nullptr)
return false;
else if (root->val == p->val || getPath(root->left, p, s) || getPath(root->right, p, s))
{
s.push(root);
return true;
}
else
return false;
};
public:
TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q)
{
getPath(root, p, s1);
getPath(root, q, s2);
TreeNode *ans;
while (!s1.empty() && !s2.empty() && s1.top() == s2.top())
{
ans = s1.top();
s1.pop();
s2.pop();
};
return ans;
}
};