标题: | Convert Sorted Array to Binary Search Tree |
通过率: | 33.8% |
难度: | 中等 |
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
给定的数组是递增的,那么平衡的二叉树一定是从中间开始,左树递归,右树右递归。看代码
1 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public TreeNode sortedArrayToBST(int[] num) { 12 return buildTree(num,0,num.length-1); 13 } 14 public TreeNode buildTree(int[] num,int left,int right){ 15 if(left>right)return null; 16 int mid=(left+right)/2; 17 TreeNode root=new TreeNode(num[mid]); 18 root.left=buildTree(num,left,mid-1); 19 root.right=buildTree(num,mid+1,right); 20 return root; 21 } 22 }