235. 二叉搜索树的最近公共祖先
为保证权益,题目请参考 235. 二叉搜索树的最近公共祖先(From LeetCode).
解决方案1
CPP
C++
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q)
{
if (root->val == p->val || root->val == q->val)
{
return root;
}
if (root->val > p->val)
{
if (root->val < q->val)
{
return root;
}
else
{
return lowestCommonAncestor(root->left, p, q);
}
}
else
{
if (root->val < q->val)
{
return lowestCommonAncestor(root->right, p, q);
}
else
{
return root;
}
}
}
};
int main()
{
return 0;
}
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
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