---
Solution: Take the middle element as the root node. Recurse on left and right sub-arrays and put as children nodes.
/**
* 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 sortedArrayToBST(nums, 0, nums.length - 1);
}
public TreeNode sortedArrayToBST(int[] nums, int i, int j) {
if (i > j) return null;
int mid = i + (j - i) / 2;
TreeNode node = new TreeNode(nums[mid]);
node.left = sortedArrayToBST(nums, i, mid - 1);
node.right = sortedArrayToBST(nums, mid + 1, j);
return node;
}
}
No comments:
Post a Comment