标签:
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
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 public class Solution { 11 public TreeNode sortedArrayToBST(int[] nums) { 12 if (nums == null) { 13 return null; 14 } 15 return builder(nums, 0, nums.length - 1); 16 } 17 18 private TreeNode builder(int[] nums, int start, int end) { 19 if (start > end) { 20 return null; 21 } 22 int mid = start + (end - start) / 2; 23 TreeNode root = new TreeNode(nums[mid]); 24 TreeNode left = builder(nums, start, mid - 1); 25 TreeNode right = builder(nums, mid + 1, end); 26 root.left = left; 27 root.right = right; 28 return root; 29 } 30 }
Convert Sorted Array to Binary Search Tree
标签:
原文地址:http://www.cnblogs.com/FLAGyuri/p/5777696.html