👨🏫 题目地址
- 时间复杂度: O ( n ) O(n) O(n)
😋 AC code
/*** 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 n = nums.length;TreeNode ans = dfs(nums, 0, n - 1);return ans;}private TreeNode dfs(int[] nums, int l, int r){if(l > r)//区间为空,返回 nullreturn null;int m = l + r >> 1;//每次都取中间的点作为当前树的根结点TreeNode ans = new TreeNode(nums[m]);ans.left = dfs(nums, l, m - 1);ans.right = dfs(nums, m + 1, r);return ans;}
}