Skip to content

Commit 8246585

Browse files
committed
Solution 2
1 parent 30e3c30 commit 8246585

File tree

1 file changed

+35
-0
lines changed
  • lowest-common-ancestor-of-a-binary-search-tree

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/*
2+
풀이
3+
- common ancestor라는 조건에 맞는 node를 찾아냅니다
4+
for common ancestor C, left subtree of C includes p (p.Val <= C.Val)
5+
and right subtree of C includes q (C.Val <= q.Val)
6+
이러한 조건을 만족하는 common ancestor는 BST에 하나만 존재합니다
7+
따라서 common ancestor를 찾으면 그게 곧 lowest common ancestor입니다
8+
Big O
9+
- N: 노드의 개수
10+
- H: 트리의 높이 (avg: logN, worst: N)
11+
- Time complexity: O(H)
12+
- Space complexity: O(H)
13+
*/
14+
15+
/**
16+
* Definition for a binary tree node.
17+
* type TreeNode struct {
18+
* Val int
19+
* Left *TreeNode
20+
* Right *TreeNode
21+
* }
22+
*/
23+
24+
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
25+
if p.Val > q.Val { // p < q가 되도록 함
26+
return lowestCommonAncestor(root, q, p)
27+
}
28+
if p.Val <= root.Val && root.Val <= q.Val { // common ancestor를 찾음
29+
return root
30+
} else if q.Val < root.Val { // left subtree 탐색
31+
return lowestCommonAncestor(root.Left, p, q)
32+
} else { // right subtree 탐색
33+
return lowestCommonAncestor(root.Right, p, q)
34+
}
35+
}

0 commit comments

Comments
 (0)