본문 바로가기

알고리즘/LeetCode

[JAVA] LeetCode 108 - Convert Sorted Array to Binary Search Tree

 

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

For this problem, a height-balanced binary tree is defined as a binary tree

in which the depth of the two subtrees of every node never differ by more than 1.

 

오름차순으로 정렬된 배열을 균형 이진 트리로 변환하라

균형 이진 트리는 두 하위 트리의 깊이(depth)가 1이 넘게 차이나지 않는 것을 의미힌다.

 

 

풀이 방법

1. 배열의 중앙 인덱스(mid)를 루트 노드로 생성한다.

2. 배열의 시작 인덱스(0)부터 mid-1 인덱스를 루트의 왼쪽 노드로 지정한다.

3. mid+1 인덱스부터 배열의 마지막 인덱스(length-1)까지 오른쪽 노드로 지정한다.

4. 이를 재귀로 구현하여 최상위의 루트 노드를 반환한다.

 

class Solution {
    public TreeNode sortedArrayToBST(int[] nums) {
        return makeBST(nums, 0, nums.length-1);
    }
    
    public TreeNode makeBST(int[] nums, int start, int end) {
        if(start > end)
            return null;
        
        int mid = (start + end) / 2;
        TreeNode root = new TreeNode(nums[mid]);
        root.left = makeBST(nums, start, mid - 1);
        root.right = makeBST(nums, mid + 1, end);
        return root;
    }
}