Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { //递归思想,构造函数,参数start和end,表示产生从start到end的二叉搜索树 //本题要求是二叉平衡搜索树,所以从中间节点开始 public TreeNode sortedArrayToBST(int[] nums) { if(nums==null||nums.length==0) return null; return getBST(nums,0,nums.length-1); } TreeNode getBST(int[] nums,int start,int end){ if(start>end) return null; int mid=(start+end)/2; TreeNode node=new TreeNode(nums[mid]); node.left=getBST(nums,start,mid-1); node.right=getBST(nums,mid+1,end); return node; } }
时间: 2024-10-25 05:58:06