Skip to content

Commit 646801d

Browse files
committed
feat(soobing): week13 > lowest-common-ancestor-of-a-binary-search-tree
1 parent 19066da commit 646801d

File tree

1 file changed

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

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* ๋ฌธ์ œ ์„ค๋ช…
3+
* - ์ด์ง„ ํƒ์ƒ‰ ํŠธ๋ฆฌ์˜ ๋‘ ๋…ธ๋“œ์˜ ์ตœ์†Œ ๊ณตํ†ต ์กฐ์ƒ์„ ์ฐพ๋Š” ๋ฌธ์ œ
4+
*
5+
* ์•„์ด๋””์–ด
6+
* 1) ๋‘ ๋…ธ๋“œ์˜ ๊ฐ’์„ ๋น„๊ตํ•˜์—ฌ ์ตœ์†Œ ๊ณตํ†ต ์กฐ์ƒ์„ ์ฐพ๋Š”๋‹ค.
7+
* - ๋‘ ๋…ธ๋“œ์˜ ๊ฐ’์ด ๋ฃจํŠธ ๋…ธ๋“œ๋ณด๋‹ค ์ž‘์œผ๋ฉด ์™ผ์ชฝ ์„œ๋ธŒํŠธ๋ฆฌ๋กœ ์ด๋™
8+
* - ๋‘ ๋…ธ๋“œ์˜ ๊ฐ’์ด ๋ฃจํŠธ ๋…ธ๋“œ๋ณด๋‹ค ํฌ๋ฉด ์˜ค๋ฅธ์ชฝ ์„œ๋ธŒํŠธ๋ฆฌ๋กœ ์ด๋™
9+
* - ๋‘ ๋…ธ๋“œ์˜ ๊ฐ’์ด ๋ฃจํŠธ ๋…ธ๋“œ์™€ ๊ฐ™์œผ๋ฉด ๋ฃจํŠธ ๋…ธ๋“œ๋ฅผ ๋ฐ˜ํ™˜
10+
*
11+
*/
12+
13+
function lowestCommonAncestor(
14+
root: TreeNode | null,
15+
p: TreeNode | null,
16+
q: TreeNode | null
17+
): TreeNode | null {
18+
if (root === null) return null;
19+
if (p === null || q === null) return null;
20+
21+
while (root !== null) {
22+
if (p.val < root.val && q.val < root.val) {
23+
root = root.left;
24+
} else if (p.val > root.val && q.val > root.val) {
25+
root = root.right;
26+
} else {
27+
return root;
28+
}
29+
}
30+
31+
return root;
32+
}

0 commit comments

Comments
ย (0)