题目链接:https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/
108. Convert Sorted Array to Binary Search Tree
Question
Total Accepted: 68378 Total
Submissions: 187560 Difficulty: Medium
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
Subscribe to see which companies asked this question
Show Tags
Show Similar Problems
Have you met this question in a real interview?
Yes
No
很有意思的一道题目。要求根据一个有序数组,构造出一棵高度平衡的BST。
每次找到数组的中间位置,这个便是BST的 根节点。左右孩子也很好找,根节点左边区域的中间节点便是左孩子,根节点的右边区域的中间节点便是右孩子。如此递归求解。
我的AC代码
public class ConvertSortedArraytoBinarySearchTree { public TreeNode sortedArrayToBST(int[] nums) { return dfs(nums, 0, nums.length - 1); } TreeNode dfs(int[] nums, int left, int right) { if (left > right) return null; int mid = (left + right) / 2; TreeNode root = new TreeNode(nums[mid]); root.left = dfs(nums, left, mid - 1); root.right = dfs(nums, mid + 1, right); return root; } }
时间: 2024-09-06 16:01:46