728x90
문제
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
균형 이진 탐색 트리를 만드는 문제이다.
재귀로 푼다.
/**
* 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 |
댓글