Home LeetCode - 108. Convert Sorted Array to Binary Search Tree
Post
Cancel

LeetCode - 108. Convert Sorted Array to Binary Search Tree

108. Convert Sorted Array to Binary Search Tree - easy

문제

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.

제한사항

입출력 예

1
2
3
4
5
6
7
8
9
10
11
Example:

Given the sorted array: [-10,-3,0,5,9],

One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:

      0
     / \
   -3   9
   /   /
 -10  5

풀이

  • Tree, BST, Recursive
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
28
29
30
31
32
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* sortedArrayToBST(vector<int>& nums) {
        if(nums.size() < 1)
            return nullptr;
        
        // 현재 vector의 중간값을 기준으로 
        // 왼쪽과 오른쪽 sub vector를 구성
        int mid = nums.size()/2;
        vector<int> left(nums.begin(), nums.begin()+mid);
        vector<int> right(nums.begin()+mid+1, nums.end());
        
        // 왼쪽의 sub vector는 현재 중간값 보다 모두 값이 작으므로
        // 왼쪽 자식노드에 저장
        // 오른쪽의 sub vector는 현재 중간값 보다 모두 값이 크므로
        // 오른쪽 자식노드에 저장
        TreeNode* item = new TreeNode(nums[mid]);
        item->left = sortedArrayToBST(left);
        item->right = sortedArrayToBST(right);
        
        return item;
    }
};
This post is licensed under CC BY 4.0 by the author.