๐ก ๋ฌธ์
๐ฏ ํ์ด ๊ณผ์
๊ตฌ๊ฐ nums ์ ๋ํด์ ์ด์งํ์ํธ๋ฆฌ๋ฅผ ๊ตฌ์ฑํ๊ธฐ ์ํด nums ์ ์ค๊ฐ๊ฐ์ ๋ฃจํธ๋ ธ๋๋กํ๊ณ
ํด๋น ๋ ธ๋๋ฅผ ์ ์ธํ ๋๋จธ์ง ๋ ๊ตฌ๊ฐ์ ๋ํด ์ฌ๊ท์ ์ผ๋ก ํธ๋ฆฌ๋ฅผ ๊ตฌ์ฑํ๋ฉด ๋ฉ๋๋ค.
์ด ๋ฐฉ์์ผ๋ก ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ ์ ์๋ ์ด์ ๋ ๋ญ๊น์?
๊ตฌ๊ฐ nums์ ๊ฐ์๋ฅผ x
๋ผ๊ณ ํ๊ณ ๊ฐ๋จํ ์ฆ๋ช
์ ํด๋ณด๊ฒ ์ต๋๋ค.
x
๊ฐ ์ง์(2n
)์ด๋ฉด ๋๋จธ์ง ๋ ๊ตฌ๊ฐ์ (n, n-1) ๋ก ๋๋๊ณ , ํ์(2n-1
)๋ผ๋ฉด (n-1, n-1) ๋ก ๋๋ฉ๋๋ค.
๋๋ฌธ์ ๋ ํธ๋ฆฌ๊ฐ์ ๋์ด ์ฐจ์ด๊ฐ 1๋ณด๋ค ํฐ ๊ฒฝ์ฐ๋ ์๊ฒ ๋ฉ๋๋ค.
๐จ๐ป ์ฝ๋
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {number[]} nums
* @return {TreeNode}
*/
var sortedArrayToBST = function(nums) {
function generateBST(lowerbound, upperbound) {
if (lowerbound > upperbound) {
return undefined
}
if (lowerbound === upperbound) {
return new TreeNode(nums[lowerbound], undefined, undefined)
}
const mid = Math.floor((lowerbound + upperbound + 1) / 2)
const leftTreeRootNode = generateBST(lowerbound, mid-1)
const rightTreeRootNode = generateBST(mid+1, upperbound)
const root = new TreeNode(nums[mid], leftTreeRootNode, rightTreeRootNode)
return root
}
const tree = generateBST(0, nums.length-1)
return tree
};
๋ฐ์ํ
'๐ algorithm > leetcode' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
LeetCode 328 - Odd Even Linked List (Medium) (0) | 2023.05.29 |
---|---|
LeetCode 704 - Binary Search (Easy) (0) | 2023.05.14 |
LeetCode 438 - Find All Anagrams in a String (Medium) (0) | 2023.05.14 |
LeetCode 42 - Trapping Rain Water (Hard) (0) | 2023.04.30 |
LeetCode 238 - Product of Array Except Self (Medium) (2) | 2023.04.24 |
๐ฌ ๋๊ธ