加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

108.Convert Sorted Array to balanced Binary Search Tree

发布时间:2020-12-14 03:49:41 所属栏目:大数据 来源:网络整理
导读:108 .?Convert Sorted Array to balanced Binary Search TreeThe 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. * pu
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,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,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;
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读