-
Notifications
You must be signed in to change notification settings - Fork 0
/
lowest_common_ancestor.cpp
44 lines (39 loc) · 1 KB
/
lowest_common_ancestor.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
34
35
36
37
38
39
40
41
42
43
44
// 236. Lowest Common Ancestor of a Binary Tree
// Author: [email protected]
#include <stdio.h>
#include <vector>
struct TreeNode
{
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
// Recursive, DFS
class Solution
{
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q)
{
if (root == nullptr || root == p || root == q)
{
return root;
}
auto* lnode = lowestCommonAncestor(root->left, p, q);
auto* rnode = lowestCommonAncestor(root->right, p, q);
if (lnode != nullptr && rnode != nullptr)
{
return root;
}
return (lnode != nullptr ? lnode : rnode);
}
};
int main(int argc, char* argv[])
{
TreeNode* root = nullptr;
TreeNode* p = nullptr;
TreeNode* q = nullptr;
auto* ancestor = Solution().lowestCommonAncestor(root, p, q);
printf("Lowest common ancestor is %p\n", ancestor);
return 0;
}