Description:
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 { public TreeNode sortedArrayToBST(int[] nums) { if(nums.length == 0) { return null; } TreeNode root = createBST(nums, 0, nums.length-1); return root; } public TreeNode createBST(int[] nums, int left, int right) { if(left > right) { return null; } int mid = (left + right) / 2; TreeNode node = new TreeNode(nums[mid]); node.left = createBST(nums, left, mid-1); node.right = createBST(nums, mid+1, right); return node; } }