Skip to content

Commit 8207243

Browse files
authored
Create 1644.Lowest-Common-Ancestor-of-a-Binary-Tree-II.cpp
1 parent af2e3c4 commit 8207243

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
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+
{
14+
vector<TreeNode*>path1 = dfs(root, p);
15+
reverse(path1.begin(), path1.end());
16+
17+
vector<TreeNode*>path2 = dfs(root, q);
18+
reverse(path2.begin(), path2.end());
19+
20+
if (path1.size()==0 ||path2.size()==0)
21+
return NULL;
22+
23+
int i=0;
24+
while (i<path1.size() && i<path2.size() && path1[i]==path2[i])
25+
i++;
26+
return path1[i-1];
27+
28+
}
29+
30+
vector<TreeNode*>dfs(TreeNode* root, TreeNode* p)
31+
{
32+
if (root==NULL) return {};
33+
if (root==p) return {root};
34+
vector<TreeNode*>path = dfs(root->left, p);
35+
if (!path.empty())
36+
{
37+
path.push_back(root);
38+
return path;
39+
}
40+
path.clear();
41+
path = dfs(root->right, p);
42+
if (!path.empty())
43+
{
44+
path.push_back(root);
45+
return path;
46+
}
47+
return {};
48+
}
49+
};

0 commit comments

Comments
 (0)