File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed
lowest-common-ancestor-of-a-binary-search-tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ *@link https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/
3+ *
4+ * 접근 방법 :
5+ * - BST니까 p,q 노드를 root 노드와 비교해서 탐색 범위 좁히기
6+ * - root.val보다 작은 경우 왼쪽 하위 트리 탐색
7+ * - root.vale보다 큰 경우 오른쪽 하위 트리 탐색
8+ * - 그 외의 경우는 값이 같으니까 root 노드 리턴
9+ *
10+ * 시간복잡도 : O(n)
11+ * - 균형 잡힌 BST의 경우 O(logn)
12+ * - 한쪽으로 치우친 트리의 경우 O(n)
13+ *
14+ * 공간복잡도 : O(n)
15+ * - 재귀 호출 스택 크기가 트리 깊이에 비례
16+ * - 균형 잡힌 BST의 경우 O(logn)
17+ * - 한쪽으로 치우친 트리의 경우 O(n)
18+ */
19+ class TreeNode {
20+ val : number ;
21+ left : TreeNode | null ;
22+ right : TreeNode | null ;
23+ constructor ( val ?: number , left ?: TreeNode | null , right ?: TreeNode | null ) {
24+ this . val = val === undefined ? 0 : val ;
25+ this . left = left === undefined ? null : left ;
26+ this . right = right === undefined ? null : right ;
27+ }
28+ }
29+
30+ function lowestCommonAncestor (
31+ root : TreeNode | null ,
32+ p : TreeNode | null ,
33+ q : TreeNode | null
34+ ) : TreeNode | null {
35+ if ( ! root || ! p || ! q ) return null ;
36+
37+ if ( p . val < root . val && q . val < root . val )
38+ return lowestCommonAncestor ( root . left , p , q ) ;
39+ else if ( p . val > root . val && q . val > root . val )
40+ return lowestCommonAncestor ( root . right , p , q ) ;
41+ else return root ;
42+ }
You can’t perform that action at this time.
0 commit comments