본문 바로가기
Algorithm/LeetCode

Leetcode - 108 . Convert Sorted Array to Binary Search Tree

by HaningYa 2020. 4. 10.
728x90

 

[Must do Easy Question]

 

How to effectively use LeetCode to prepare for interviews!! - LeetCode Discuss

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

Convert Sorted Array to Binary Search Tree - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com


문제

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.

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

 


균형 이진 탐색 트리를 만드는 문제이다. 

 

[이진 탐색 트리]

 

균형 이진 탐색 트리(AVL 트리)

본 내용은 Deep Into Algorithm from MIT 강의를 들으며 정리한 내용이다. 이전 포스팅에 다룬 이진 탐색 트리(BST)에서 이어지는 내용이다. 혹시 보지 않았거나 가물가물하다면 이전 포스팅을 한 번 보고 오는 것..

mrlee.kr

재귀로 푼다.

 

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode sortedArrayToBST(int[] nums) {
        if(nums.length == 0){
            return null;
        }
        return makeBST(nums, 0, nums.length-1);
    }
    
    public TreeNode makeBST(int[] nums, int left, int right){
        if(left>right){
            return null;
        }
        int mid = left + (right - left)/2;
        TreeNode node = new TreeNode(nums[mid]);
        node.left = makeBST(nums,left,mid-1);
        node.right = makeBST(nums,mid+1,right);
        return node;
    }
}

 

728x90

'Algorithm > LeetCode' 카테고리의 다른 글

Leetcode - 189 . Rotate Array  (0) 2020.04.14
Leetcode - 371 . Sum of Two Integers  (0) 2020.04.14
Leetcode - 88 . Merge Sorted Array  (0) 2020.04.10
Leetcode - 242 . Valid Anagram  (0) 2020.04.10
Leetcode - 202. Count Primes  (0) 2020.04.08

댓글