leetcode-108-easy
阿新 • • 發佈:2022-12-01
Convert Sorted Array to Binary Search Tree
Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree. Example 1: Input: nums = [-10,-3,0,5,9] Output: [0,-3,9,-10,null,5] Explanation: [0,-10,5,null,-3,null,9] is also accepted: Example 2: Input: nums = [1,3] Output: [3,1] Explanation: [1,null,3] and [3,1] are both height-balanced BSTs. Constraints: 1 <= nums.length <= 104 -104 <= nums[i] <= 104 nums is sorted in a strictly increasing order.
思路一:要構建二叉排序樹,考慮使用遞迴的思想,每次取一箇中值作為節點的值,左邊的所有值用於構造節點的左子樹,右邊的所有值用於構造節點的右子樹。
由於樹是排序的,左節點的值一定要小於右節點,所以判斷中值的時候注意取整條件
public TreeNode sortedArrayToBST(int[] nums) { return sortedArrayToBST(nums, 0, nums.length - 1); } public TreeNode sortedArrayToBST(int[] nums, int begin, int end) { int mid = (begin + end) % 2 == 0 ? (begin + end) / 2 : (begin + end) / 2 + 1; TreeNode node = new TreeNode(nums[mid]); if (begin < mid) { node.left = sortedArrayToBST(nums, begin, mid - 1); } if (mid < end) { node.right = sortedArrayToBST(nums, mid + 1, end); } return node; }