Skip to content

Commit 689582d

Browse files
committed
refactor: Lowest Common Ancestor of a Binary Search Tree
1 parent 631f5e4 commit 689582d

File tree

1 file changed

+9
-36
lines changed

1 file changed

+9
-36
lines changed
Lines changed: 9 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
1-
// Time complexity: O(logn)
2-
// Space complexity: O(logn)
1+
// h : height of BST
2+
// Time complexity: O(h)
3+
// Space complexity: O(h)
34

45
/**
56
* Definition for a binary tree node.
@@ -16,41 +17,13 @@
1617
* @return {TreeNode}
1718
*/
1819
var lowestCommonAncestor = function (root, p, q) {
19-
// 1. 각자 부모 리스트 완성
20-
const search = (target, parent) => {
21-
const dfs = (current) => {
22-
if (target.val > current.val) {
23-
dfs(current.right);
24-
}
25-
26-
if (target.val < current.val) {
27-
dfs(current.left);
28-
}
29-
30-
parent.push(current);
31-
};
32-
33-
dfs(root);
34-
};
35-
36-
const parentP = [];
37-
const parentQ = [];
38-
39-
search(p, parentP);
40-
search(q, parentQ);
41-
42-
// 2. 공통 부모 탐색
43-
let answer = null;
20+
if (root.val < p.val && root.val < q.val && root.left) {
21+
return lowestCommonAncestor(root.right, p, q);
22+
}
4423

45-
while (
46-
parentP.at(-1) &&
47-
parentQ.at(-1) &&
48-
parentP.at(-1).val === parentQ.at(-1).val
49-
) {
50-
answer = parentP.at(-1);
51-
parentP.pop();
52-
parentQ.pop();
24+
if (root.val > p.val && root.val > q.val && root.right) {
25+
return lowestCommonAncestor(root.left, p, q);
5326
}
5427

55-
return answer;
28+
return root;
5629
};

0 commit comments

Comments
 (0)