首页 > 其他 > 详细

108. Convert Sorted Array to balanced Binary Search Tree

时间:2018-08-17 00:18:40      阅读:200      评论:0      收藏:0      [点我收藏+]
108. Convert Sorted Array to balanced Binary Search Tree

The tricky part is the base case . 
Write induction part first and then test arrays of different size, 0, 1,2, 3 
And finalize the base case 


/**
 * 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){
      // this base case, try 4 cases. When size is 0, 1, 2 , 3 
      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 balanced Binary Search Tree

原文:https://www.cnblogs.com/tobeabetterpig/p/9490881.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!