Skip to content

Commit

Permalink
add post '(Leetcode) 235 - Lowest Common Ancestor of a Binary Search …
Browse files Browse the repository at this point in the history
…Tree'
  • Loading branch information
dev-jonghoonpark committed Jun 9, 2024
1 parent 9554f17 commit b1442ad
Showing 1 changed file with 49 additions and 0 deletions.
49 changes: 49 additions & 0 deletions _posts/2024-06-10-leetcode-235.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
---
layout: post
title: (Leetcode) 235 - Lowest Common Ancestor of a Binary Search Tree
categories: [스터디-알고리즘]
tags: [자바, java, 리트코드, Leetcode, 알고리즘, algorithm, tree, bst, lca]
date: 2024-06-10 01:00:00 +0900
toc: true
---

기회가 되어 [달레님의 스터디](https://github.com/DaleStudy/leetcode-study)에 참여하여 시간이 될 때마다 한문제씩 풀어보고 있다.

[https://neetcode.io/practice](https://neetcode.io/practice)

---

[https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/)

## 내가 작성한 풀이

이 문제에서는 [LCA](https://en.wikipedia.org/wiki/Lowest_common_ancestor) 에 대한 개념이 있어야 한다.

LCA가 되는 케이스를 2가지로 생각하였다. 하나는 노드의 양쪽에 나눠져 있는 경우, 다른 하나는 하나의 노드 아래 포함되어 있는 경우이다.

```java
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
return dfs(root, p, q);
}

private TreeNode dfs(TreeNode node, TreeNode p, TreeNode q) {
if (node == null) {
return null;
}

TreeNode left = dfs(node.left, p, q);
TreeNode right = dfs(node.right, p, q);

if ((left != null && right != null) || node.val == p.val || node.val == q.val) {
return node;
}

return left != null ? left : right;
}
}
```

### TC, SC

시간 복잡도는 O(n)이고, 공간 복잡도는 O(n)이다. 트리가 균등할 경우 O(logn)에 가까워진다.

0 comments on commit b1442ad

Please sign in to comment.