PS/LeetCode

LeetCode / Binary Search Tree / 108번 / Convert Sorted Array to Binary Search Tree / JS

KimMinJun 2023. 4. 29. 17:58

< 문제 바로가기 >

 

Convert Sorted Array to Binary Search Tree - LeetCode

Can you solve this real interview question? Convert Sorted Array to Binary Search Tree - Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree.   Example 1: [https://assets.leetcod

leetcode.com

 

< 문제 간단설명 >

input으로 들어온 정렬된 배열을 이진 탐색 트리로 변환하는 문제이다.

 

/**
 * 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) {
  if (nums.length === 0) {
    return null;
  }

  let mid = Math.floor(nums.length / 2);
  let root = new TreeNode(nums[mid], null, null);

  // 가운데는 root node 이기 때문에 가운데를 빼고 왼쪽, 오른쪽으로 나눠줌
  let left = nums.slice(0, mid);
  let right = nums.slice(mid + 1);

  root.left = sortedArrayToBST(left);
  root.right = sortedArrayToBST(right);

  return root;
};