Skip to content

Commit 287c045

Browse files
authored
[ PS ] : Lowest Common Ancestor of a Binary Search Tree
1 parent 9f87153 commit 287c045

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val) {
4+
* this.val = val;
5+
* this.left = this.right = null;
6+
* }
7+
*/
8+
9+
/**
10+
* @param {TreeNode} root
11+
* @param {TreeNode} p
12+
* @param {TreeNode} q
13+
* @return {TreeNode}
14+
*/
15+
const lowestCommonAncestor = function (root, p, q) {
16+
// ์ด์ง„ํƒ์ƒ‰ํŠธ๋ฆฌ(BST)์˜ ํŠน์ง•์„ ํ™œ์šฉํ•˜์—ฌ
17+
// p, q์˜ ๊ฐ’๊ณผ root ๊ฐ’์„ ๋น„๊ตํ•ด p, q๊ฐ€ ์†ํ•œ ํŠธ๋ฆฌ(left/right)๋ฅผ ํŒ๋‹จ
18+
if (p.val < root.val && q.val < root.val) {
19+
return lowestCommonAncestor(root.left, p, q);
20+
} else if (p.val > root.val && q.val > root.val) {
21+
return lowestCommonAncestor(root.right, p, q);
22+
} else {
23+
return root;
24+
}
25+
};
26+
27+
// ์‹œ๊ฐ„๋ณต์žก๋„: O(h) (h: ํŠธ๋ฆฌ์˜ ๋†’์ด, ์ฆ‰ ์žฌ๊ท€ ์Šคํƒ ๊นŠ์ด)
28+
// ๊ณต๊ฐ„๋ณต์žก๋„: O(h) (h: ํŠธ๋ฆฌ์˜ ๋†’์ด, ์ฆ‰ ์žฌ๊ท€ ์Šคํƒ ๊นŠ์ด)

0 commit comments

Comments
ย (0)