Skip to content

Commit 5de817f

Browse files
committed
#249 solution
1 parent 86579d9 commit 5de817f

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/*
2+
풀이 :
3+
현재 root를 기준으로 p, q가 어딨는지 판별
4+
p, q값이 모두 root 보다 작으면 왼쪽, 모두 root 보다 크면 오른쪽 노드로 이동
5+
그 외의 경우 (root 값이 p 또는 q와 같을 경우, p와 q사이에 있는 경우)에는
6+
현재 root가 LCA이므로 root 리턴
7+
8+
트리 높이 : H
9+
10+
TC : O (H)
11+
반복문이 트리 높이에 비례
12+
13+
SC : O (1)
14+
*/
15+
16+
17+
#include <algorithm>
18+
using namespace std;
19+
/**
20+
* Definition for a binary tree node.
21+
* struct TreeNode {
22+
* int val;
23+
* TreeNode *left;
24+
* TreeNode *right;
25+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
26+
* };
27+
*/
28+
29+
class Solution {
30+
public:
31+
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
32+
int small = min(p->val, q->val);
33+
int big = max(p->val, q->val);
34+
while (root) {
35+
if (root->val > big)
36+
root = root->left;
37+
else if (root->val < small)
38+
root = root->right;
39+
else
40+
break;
41+
}
42+
return root;
43+
}
44+
};

0 commit comments

Comments
 (0)