ð 108. å°æåºæ°ç»èœ¬æ¢äžºäºåæ玢æ
2022幎10æ10æ¥
- algorithm
ð 108. å°æåºæ°ç»èœ¬æ¢äžºäºåæ玢æ
éŸåºŠ: ð
é®é¢æè¿°
解æ³
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
// æè·¯ïŒ
// ä»äžç¹å€åå²ïŒä¿è¯å¹³è¡¡
int len = nums.length;
return mySol(nums, 0, len - 1);
}
private TreeNode mySol(int[] nums, int left, int right) {
// éåœç»æ¢æ¡ä»¶
if(left > right) {
return null;
}
if(left == right) {
return new TreeNode(nums[left]);
}
// left < right
int mid = left + ((right - left) >> 1);
TreeNode root = new TreeNode(nums[mid]);
root.left = mySol(nums, left, mid - 1);
root.right = mySol(nums, mid + 1, right);
return root;
}
}