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) {
/**
* 高度平衡二叉搜索樹
* 指左右子樹的高度差不超過1
* 所以每次從中間構造根節點
* 兩邊構造左右子樹
*/
return BST(nums,0,nums.length-1);
}
private TreeNode BST(int[] nums, int i, int j){
if(i > j){
return null;
}
int mid = (j + i + 1)/2;
TreeNode root = new TreeNode(nums[mid]);
root.left = BST(nums,i,mid-1);
root.right = BST(nums,mid+1,j);
return root;
}
}