Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
這題可以一眼看出是要用遞歸,不會是叫你寫一個BST的插入。每次選出sorted array中間的那個元素作為目前的node,這個node的左兒子是左半邊數組的中間元素,右兒子是右半邊數組的中間元素。這樣就有Subproblem了。
coding的時候注意subproblem的範圍是(low, mid - 1)和(mid + 1, high),因為mid元素已經用過了。
發現自己遞歸還是要多練練,想到了這是遞歸也用了很久才寫出代碼,sigh
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode sortedArrayToBST(int[] num) {
return helper(num, 0, num.length - 1);
}
public TreeNode helper(int[] num, int low, int high){
if(low > high)
return null;
int mid = (low + high) / 2;
TreeNode node = new TreeNode(num[mid]);
node.left = helper(num, low, mid - 1);
node.right = helper(num, mid + 1, high);
return node;
}
}