-
[Day3] 108. Convert Sorted Array to Binary Search Tree@StudY/.algorithm 2019. 2. 15. 14:37
108. Convert Sorted Array to Binary Search Tree
/**
* 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 ) {
TreeNode newT = new TreeNode(nums[nums.length/2]);
int[] left = new int[nums.length/2];
int[] right;
if (nums.length%2==0) right= new int[nums.length/2-1];
else right= new int[nums.length/2];
for (int i=0; i< nums.length; i++) {
if (i<nums.length/2) left[i] = nums[i];
else if (i>nums.length/2) right[i-nums.length/2-1] = nums[i];
}
if (nums.length>1) newT.left = sortedArrayToBST(left);
if (nums.length>2) newT.right = sortedArrayToBST(right);
return newT;
}
return null;
}
}
Accepted 1 ms 37.9 MB java '@StudY > .algorithm' 카테고리의 다른 글
[Day7] 876. Middle of the Linked List / 86. Partition List (LeetCode) (0) 2019.02.22 [Day6] 981. Time Based Key-Value Store (0) 2019.02.20 [Day4] 529. Minesweeper (0) 2019.02.18 [Day2] 617. Merge Two Binary Trees/ 888. Fair Candy Swap (LeetCode) (0) 2019.02.14 [Day1] 319. Bulb Switcher (LeetCode) (0) 2019.02.12 댓글