Skip to content

Commit 0e1484d

Browse files
committed
Lowest Common Ancestor of a Binary Search Tree
1 parent b56d702 commit 0e1484d

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
2+
// Definition for a binary tree node.
3+
class TreeNode {
4+
int val;
5+
TreeNode left;
6+
TreeNode right;
7+
8+
TreeNode(int x) {
9+
val = x;
10+
}
11+
}
12+
13+
14+
class Solution {
15+
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
16+
// 플이: p,q 둘다 root 보다 값이 적으면 왼쪽 서브트리를, 둘다 크면 오른쪽 서브트리를 탐색해야한다.
17+
// 그렇지 않으면 해당 root가 최저 공통 조상이 된다.
18+
// TC: O(H), H: 트리의 높이
19+
// SC: O(1)
20+
var node = root;
21+
while (node != null) {
22+
if (p.val < node.val && q.val < node.val) {
23+
node = node.left;
24+
} else if (p.val > node.val && q.val > node.val) {
25+
node = node.right;
26+
} else {
27+
break;
28+
}
29+
}
30+
31+
return node;
32+
}
33+
}

0 commit comments

Comments
 (0)