๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿƒ algorithm/leetcode

LeetCode 108 - Convert Sorted Array to Binary Search Tree (Easy)

by HandHand 2023. 6. 6.

 

๐Ÿ’ก ๋ฌธ์ œ

LeetCode - 108๋ฒˆ

 

๐ŸŽฏ ํ’€์ด ๊ณผ์ •

๊ตฌ๊ฐ„ 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

๐Ÿ’ฌ ๋Œ“๊ธ€