108. Convert Sorted Array to balanced Binary Search Tree
Posted tobeabetterpig
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了108. Convert Sorted Array to balanced Binary Search Tree相关的知识,希望对你有一定的参考价值。
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的主要内容,如果未能解决你的问题,请参考以下文章
108. Convert Sorted Array to Binary Search [Python]
108. Convert Sorted Array to Binary Search Tree
108. Convert Sorted Array to Binary Search Tree
108. Convert Sorted Array to Binary Search Tree