Skip to content

Commit 98398cc

Browse files
committed
lowest-common-ancestor-of-a-binary-search-tree solution2
1 parent 4d203e9 commit 98398cc

File tree

1 file changed

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

1 file changed

+34
-0
lines changed

โ€Žlowest-common-ancestor-of-a-binary-search-tree/jdy8739.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,3 +40,37 @@ var lowestCommonAncestor = function (root, p, q) {
4040
// ์‹œ๊ฐ„๋ณต์žก๋„ O(logn) -> ์ด์ง„ํŠธ๋ฆฌ๋ฅผ ์ด์ง„ํƒ์ƒ‰ํ•˜๋ฉด์„œ ํŠธ๋ฆฌ์˜ ๋…ธ๋“œ๋ฅผ ๋ฐฉ๋ฌธํ•˜๊ธฐ๋–„๋ฌธ(๋™์ผํ•œ ๊นŠ์ด์—์„œ ํ•œ ๋ฒˆ ์™ผ์ชฝ์„ ๋ฐฉ๋ฌธํ•˜์˜€๋‹ค๋ฉด, ๊ทธ ๊นŠ์ด์—์„œ ์˜ค๋ฅธ์ชฝ์„ ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์Œ)
4141
// ๊ณต๊ฐ„๋ณต์žก๋„ O(h) -> ์žฌ๊ท€ํ˜ธ์ถœ์„ ์‚ฌ์šฉํ•˜์˜€์œผ๋ฏ€๋กœ ํŠธ๋ฆฌ์˜ ๋†’์ด๋งŒํผ ์ตœ๋Œ€ ์ฝœ์Šคํƒ์˜ ์Œ“์ž„์ด ๋ฐœ์ƒ
4242

43+
/**
44+
* Definition for a binary tree node.
45+
* function TreeNode(val) {
46+
* this.val = val;
47+
* this.left = this.right = null;
48+
* }
49+
*/
50+
51+
/**
52+
* @param {TreeNode} root
53+
* @param {TreeNode} p
54+
* @param {TreeNode} q
55+
* @return {TreeNode}
56+
*/
57+
var lowestCommonAncestor = function (root, p, q) {
58+
let node = root;
59+
60+
while (node) {
61+
if (node.val >= p.val && node.val <= q.val) {
62+
return node;
63+
} else if (node.val < p.val && node.val < q.val) {
64+
node = node.right;
65+
} else if (node.val > p.val && node.val > q.val) {
66+
node = node.left;
67+
} else {
68+
break;
69+
}
70+
}
71+
72+
return node;
73+
};
74+
75+
// ์‹œ๊ฐ„๋ณต์žก๋„ O(logn) -> ์ด์ง„ํŠธ๋ฆฌ๋ฅผ ์ด์ง„ํƒ์ƒ‰ํ•˜๋ฉด์„œ ํŠธ๋ฆฌ์˜ ๋…ธ๋“œ๋ฅผ ๋ฐฉ๋ฌธํ•˜๊ธฐ๋–„๋ฌธ(๋™์ผํ•œ ๊นŠ์ด์—์„œ ํ•œ ๋ฒˆ ์™ผ์ชฝ์„ ๋ฐฉ๋ฌธํ•˜์˜€๋‹ค๋ฉด, ๊ทธ ๊นŠ์ด์—์„œ ์˜ค๋ฅธ์ชฝ์„ ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์Œ)
76+
// ๊ณต๊ฐ„๋ณต์žก๋„ O(1) -> ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์œ„ํ•ด ์š”๊ตฌ๋˜๋Š” ์ž๋ฃŒ๊ตฌ์กฐ๋‚˜ ์ฝœ์Šคํƒ์˜ ์Œ“์ž„์ด ๋ฐœ์ƒํ•˜์ง€ ์•Š์Œ

0 commit comments

Comments
ย (0)