题目:Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
题意及分析:给出一个有序序列,构造一棵平衡二叉查找树。二叉查找树:对于任意一个节点,都有左子节点小于右节点;二叉平衡树:对于任意一个节点,左右子树的高度差不超过1。这里可以将序列的中点当做根节点,然后递归左右子序列。
代码:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public TreeNode sortedArrayToBST(int[] nums) { return bulidTree(nums,0,nums.length-1); } public TreeNode bulidTree(int[] nums,int start,int end){ if(start>end) return null; int mid = (start+end)/2; TreeNode root = new TreeNode(nums[mid]); root.left = bulidTree(nums,start,mid-1); root.right = bulidTree(nums,mid+1,end); return root; } }