将有序数组转换为二叉搜索树
给你一个整数数组 nums ,其中元素已经按 升序 排列,请你将其转换为一棵
平衡
二叉搜索树。
示例 1:

1 2 3
| 输入:nums = [-10,-3,0,5,9] 输出:[0,-3,9,-10,null,5] 解释:[0,-10,5,null,-3,null,9] 也将被视为正确答案:
|
示例 2:

1 2 3
| 输入:nums = [1,3] 输出:[3,1] 解释:[1,null,3] 和 [3,1] 都是高度平衡二叉搜索树。
|
提示:
1 <= nums.length <= 104
-104 <= nums[i] <= 104
nums 按 严格递增 顺序排列
为了保持树的平衡,每次选取区间的中点作为根节点。
建树的过程是一个递归方法,返回结果是树的根节点,结束条件是左边界超过右边界。根的左孩子等于递归建立根的左孩子,根的右孩子等于递归建立根的右孩子。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| class Solution { public TreeNode sortedArrayToBST(int[] nums) { return build(nums, 0, nums.length - 1); }
private TreeNode build(int[] nums, int l, int r) { if (l > r) { return null; } int mid = l + r >> 1; TreeNode root = new TreeNode(nums[mid]); root.left = build(nums, l, mid - 1); root.right = build(nums, mid + 1, r); return root; } }
|