Skip to content

Commit bd49386

Browse files
committed
feat: Upload lowest-common-ancestor-of-a-binary-search-tree (typescript)
1 parent c94cd08 commit bd49386

File tree

1 file changed

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

1 file changed

+69
-0
lines changed
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
/**
2+
* Source: https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree
3+
* Solution: DFS를 이용해서 두 노드까지의 경로를 구해 순차적으로 비교하면서 가장 마지막 동일 노드를 추출
4+
*
5+
* 시간복잡도: O(N) - 최악인 경우, 전체 노드수 탐색
6+
* 공간복잡도: O(N) - 최악인 경우, 전체 노드수 보관
7+
*
8+
* 다른 풀이
9+
* - 재귀로도 해결할 것으로 보이지만 바로 구현체가 떠오르지 않음
10+
*/
11+
12+
/**
13+
* Definition for a binary tree node.
14+
* class TreeNode {
15+
* val: number
16+
* left: TreeNode | null
17+
* right: TreeNode | null
18+
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
19+
* this.val = (val===undefined ? 0 : val)
20+
* this.left = (left===undefined ? null : left)
21+
* this.right = (right===undefined ? null : right)
22+
* }
23+
* }
24+
*/
25+
26+
function lowestCommonAncestor(
27+
root: TreeNode | null,
28+
p: TreeNode | null,
29+
q: TreeNode | null
30+
): TreeNode | null {
31+
if (!root || !p || !q) return null;
32+
let stack = new Array(root);
33+
let pRoute: Array<TreeNode> | null;
34+
let qRoute: Array<TreeNode> | null;
35+
let answer: TreeNode | null;
36+
const visited = new Set();
37+
38+
while (stack.length) {
39+
const left = stack.at(-1).left;
40+
if (left && !visited.has(left.val)) {
41+
stack.push(left);
42+
continue;
43+
}
44+
const right = stack.at(-1).right;
45+
if (right && !visited.has(right.val)) {
46+
stack.push(right);
47+
continue;
48+
}
49+
const now = stack.pop();
50+
visited.add(now.val);
51+
if (now.val === q.val) {
52+
qRoute = [...stack, now];
53+
continue;
54+
}
55+
if (now.val === p.val) {
56+
pRoute = [...stack, now];
57+
continue;
58+
}
59+
}
60+
const shortLength =
61+
pRoute.length > qRoute.length ? qRoute.length : pRoute.length;
62+
for (let i = 0; i < shortLength; i++) {
63+
if (pRoute.at(i) !== qRoute.at(i)) {
64+
answer = pRoute.at(i - 1);
65+
break;
66+
}
67+
}
68+
return answer ? answer : pRoute.at(shortLength - 1);
69+
}

0 commit comments

Comments
 (0)