Title Description
An ordered array in accordance with the ascending order, is converted to a highly balanced binary search tree.
In this problem, a highly balanced binary tree is a binary tree refers to the left and right sub-tree of each node is the height difference between the absolute value of not more than 1.
Example:
Given an ordered array: [-10, -3,0,5,9],
One possible answer is: [0, -3,9, -10, null, 5], it can be expressed below this height balanced binary search tree:
0
/ \
-3 9
/ /
-10 5
Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/convert-sorted-array-to-binary-search-tree
Problem-solving ideas:
1, the root root = nums [mid]
2, root.left = intermediate value of the remaining portion of the left
3, root.right = intermediate value of the remaining portion of the left
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 class Solution { 11 public TreeNode sortedArrayToBST(int[] nums) { 12 if(nums.length==0) return null; 13 else{ 14 return digui(nums,0,nums.length-1); 15 } 16 } 17 18 public TreeNode digui(int[] nums,int left,int right){ 19 if(left>right){ 20 return null; 21 } 22 23 int mid=left+(right-left)/2; //避免溢出风险;;;; 24 TreeNode root = new TreeNode(nums[mid]); 25 root.left=digui(nums,left,mid-1); 26 root.right=digui(nums,mid+1,right); 27 return root; 28 } 29 }