题目:
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
分析:
平衡二叉树的特点:左右子树的高度差不能超过1
采用二分查找思想和递归思想
代码:
public static TreeNode sortedArrayToBST(int[] nums) { if(nums.length== 0){ return null; } if(nums.length == 1){ TreeNode rootNode = new TreeNode(nums[0]); return rootNode; } int intPosition =0; intPosition = nums.length/2; TreeNode rootNode = new TreeNode(nums[intPosition]); rootNode.left = sortedArrayToBST(Arrays.copyOfRange(nums, 0, intPosition)); rootNode.right = sortedArrayToBST(Arrays.copyOfRange(nums, intPosition, nums.length)); return rootNode; }
PS:这个题目简单就是因为输入的数组是排好序的