-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprogram.cpp
More file actions
59 lines (54 loc) · 1.4 KB
/
program.cpp
File metadata and controls
59 lines (54 loc) · 1.4 KB
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include "../include/prevector.h"
/**
* Definition for a binary tree node.
*/
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
bool ergodic(vector<TreeNode*>& path, TreeNode* root, TreeNode* d)
{
if (root == NULL) return false;
if (root == d) {
path.push_back(root);
return true;
}
if (ergodic(path, root->left, d)) {
path.push_back(root);
return true;
}
if (ergodic(path, root->right, d)) {
path.push_back(root);
return true;
}
return false;
}
vector<TreeNode*> pathToElem(TreeNode* root, TreeNode* d)
{
vector<TreeNode*> path;
ergodic(path, root, d);
return path;
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q)
{
auto pathToP = pathToElem(root, p);
auto pathToQ = pathToElem(root, q);
size_t i = 0;
for (i = 0; i != std::min(pathToQ.size(), pathToP.size()); i++)
{
if (*(pathToQ.rbegin() + i) != *(pathToP.rbegin() + i)) break;
}
return *(pathToQ.rbegin() + i - 1);
}
int main()
{
auto root = new TreeNode(0);
root->left = new TreeNode(1);
root->right = new TreeNode(2);
root->right->left = new TreeNode(3);
root->right->right = new TreeNode(4);
cout << (root->right == lowestCommonAncestor(root, root->right->left, root->right->right)) << endl;
return 0;
}