码迷,mamicode.com
首页 > 其他好文 > 详细

108. Convert Sorted Array to Binary Search Tree

时间:2018-08-09 19:32:38      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:help   solution   efi   col   ini   tco   search   bsp   val   

108. Convert Sorted Array to Binary Search Tree


https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/discuss/35220/My-Accepted-Java-Solution

https://www.youtube.com/watch?v=VCTP81Ij-EM




/**
 * 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;
      }
      
      TreeNode root = helper(nums, 0, nums.length - 1); // nums.length - 1
      return root;
    }
  
    private TreeNode helper(int[] nums, int start, int end){
      if(start > end) return null;
      
      int mid = start + (end - start) / 2;
      TreeNode root = new TreeNode(nums[mid]);
      root.left = helper(nums, start, mid - 1);  // mid - 1
      root.right = helper(nums, mid + 1, end);  // mid + 1
      return root;
    }
}

 

108. Convert Sorted Array to Binary Search Tree

标签:help   solution   efi   col   ini   tco   search   bsp   val   

原文地址:https://www.cnblogs.com/tobeabetterpig/p/9450943.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!