(LeetCode) 108. Convert Sorted Array to Binary Search Tree

108. Convert Sorted Array to Binary Search Tree

  • Explore : Interview > Top Interveiw Questions > Easy Collection
  • 분류 : Trees
  • 난이도 : Easy

Problem

Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree.

A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one.

Example 1

1
2
3
Input: nums = [-10,-3,0,5,9]
Output: [0,-3,9,-10,null,5]
Explanation: [0,-10,5,null,-3,null,9] is also accepted:

Example 2

1
2
3
Input: nums = [1,3]
Output: [3,1]
Explanation: [1,3] and [3,1] are both a height-balanced BSTs.

Constraints

  • 1 <= nums.length <= 10^4
  • -10^4 <= nums[i] <= 10^4
  • nums is sorted in a strictly increasing order.

Solution

Exapnder
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
* Example:
* var ti = TreeNode(5)
* var v = ti.`val`
* Definition for a binary tree node.
* class TreeNode(var `val`: Int) {
* var left: TreeNode? = null
* var right: TreeNode? = null
* }
*/
class Solution {
fun sortedArrayToBST(nums: IntArray): TreeNode? {
return recursive(nums, 0, nums.size - 1)
}

fun recursive(nums: IntArray, low: Int, high: Int): TreeNode? {
if (low > high) {
return null
}
var mid = low + (high - low) / 2

return TreeNode(nums[mid]).apply {
left = recursive(nums, low, mid - 1)
right = recursive(nums, mid + 1, high)
}
}
}

Point of Thinking

  • 오름차순 정렬이니, 주어진 배열의 정중앙에 위치한 값이 root 노드이다.
  • root노드를 기준으로 좌측과 우측에 대해서 재귀 호출로 정렬하면 Accepted.