Skip to content

Commit b1442ad

Browse files
add post '(Leetcode) 235 - Lowest Common Ancestor of a Binary Search Tree'
1 parent 9554f17 commit b1442ad

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

_posts/2024-06-10-leetcode-235.md

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
---
2+
layout: post
3+
title: (Leetcode) 235 - Lowest Common Ancestor of a Binary Search Tree
4+
categories: [스터디-알고리즘]
5+
tags: [자바, java, 리트코드, Leetcode, 알고리즘, algorithm, tree, bst, lca]
6+
date: 2024-06-10 01:00:00 +0900
7+
toc: true
8+
---
9+
10+
기회가 되어 [달레님의 스터디](https://github.com/DaleStudy/leetcode-study)에 참여하여 시간이 될 때마다 한문제씩 풀어보고 있다.
11+
12+
[https://neetcode.io/practice](https://neetcode.io/practice)
13+
14+
---
15+
16+
[https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/)
17+
18+
## 내가 작성한 풀이
19+
20+
이 문제에서는 [LCA](https://en.wikipedia.org/wiki/Lowest_common_ancestor) 에 대한 개념이 있어야 한다.
21+
22+
LCA가 되는 케이스를 2가지로 생각하였다. 하나는 노드의 양쪽에 나눠져 있는 경우, 다른 하나는 하나의 노드 아래 포함되어 있는 경우이다.
23+
24+
```java
25+
class Solution {
26+
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
27+
return dfs(root, p, q);
28+
}
29+
30+
private TreeNode dfs(TreeNode node, TreeNode p, TreeNode q) {
31+
if (node == null) {
32+
return null;
33+
}
34+
35+
TreeNode left = dfs(node.left, p, q);
36+
TreeNode right = dfs(node.right, p, q);
37+
38+
if ((left != null && right != null) || node.val == p.val || node.val == q.val) {
39+
return node;
40+
}
41+
42+
return left != null ? left : right;
43+
}
44+
}
45+
```
46+
47+
### TC, SC
48+
49+
시간 복잡도는 O(n)이고, 공간 복잡도는 O(n)이다. 트리가 균등할 경우 O(logn)에 가까워진다.

0 commit comments

Comments
 (0)