Skip to content

Commit 1cb8871

Browse files
committed
lowest-common-ancestor-of-a-binary-search-tree solution
1 parent 909f08f commit 1cb8871

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+
* https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/
3+
* Definition for a binary tree node.
4+
* function TreeNode(val) {
5+
* this.val = val;
6+
* this.left = this.right = null;
7+
* }
8+
*/
9+
10+
/**
11+
* @param {TreeNode} root
12+
* @param {TreeNode} p
13+
* @param {TreeNode} q
14+
* @return {TreeNode}
15+
*/
16+
var lowestCommonAncestor = function (root, p, q) {
17+
let current = root;
18+
19+
while (current) {
20+
// ๋‘ ๋…ธ๋“œ์˜ ๊ฐ’์ด ํ˜„์žฌ ๋…ธ๋“œ๋ณด๋‹ค ๋ชจ๋‘ ์ž‘์œผ๋ฉด ์™ผ์ชฝ ์„œ๋ธŒํŠธ๋ฆฌ๋กœ ์ด๋™
21+
if (p.val < current.val && q.val < current.val) {
22+
current = current.left;
23+
}
24+
// ๋‘ ๋…ธ๋“œ์˜ ๊ฐ’์ด ํ˜„์žฌ ๋…ธ๋“œ๋ณด๋‹ค ๋ชจ๋‘ ํฌ๋ฉด ์˜ค๋ฅธ์ชฝ ์„œ๋ธŒํŠธ๋ฆฌ๋กœ ์ด๋™
25+
else if (p.val > current.val && q.val > current.val) {
26+
current = current.right;
27+
}
28+
// ํ˜„์žฌ ๋…ธ๋“œ๊ฐ€ ๋ถ„๊ธฐ์ ์ด๋ฉด ๊ทธ๊ฒŒ LCA!
29+
else {
30+
return current;
31+
}
32+
}
33+
34+
return null; // ๋งŒ์•ฝ ํŠธ๋ฆฌ์— ์—†๋‹ค๋ฉด null ๋ฐ˜ํ™˜ (์ผ๋ฐ˜์ ์œผ๋กœ BST์—๋Š” ํ•ญ์ƒ ์กด์žฌํ•œ๋‹ค๊ณ  ๊ฐ€์ •)
35+
};

0 commit comments

Comments
ย (0)