Solution: 1/**2* Definition for binary tree3* public class TreeNode {4* int val;5* TreeNode left;6* TreeNode right;7* TreeNode(int x) { val = x; }8* }9*/10publicclassSolution {11publicTreeNode sortedArrayToBST(
Main.sortedArrayToBST(num1) 验证结果: Runtime:72 ms, faster than24.34%ofPython3online submissions forConvert Sorted Array to Binary Search Tree. Memory Usage:15.4 MB, less than5.70%ofPython3online submissions forConvert Sorted Array to Binary Search Tree. 速度太慢了,看来本题优化的空间还很大,...
Given an array where elements are sorted in ascending order, convert it to a height balanced BST. For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees ofeverynode never differ by more than 1. Example: Given the sorted array:...
思路很简单,用二分法,每次选中间的点作为根结点,用左、右结点递归。 TreeNode* sortedArrayToBST(vector<int> &num) {returnsortedArrayToBST(num.begin(), num.end()); } template<typename RandomAccessIterator>TreeNode*sortedArrayToBST(RandomAccessIterator first, RandomAccessIterator last) {constauto leng...
Given an integer arraynumswhere the elements are sorted inascending order, convertit to aheight-balancedbinary 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: ...
LeetCode 109. Convert Sorted List to Binary Search Tree Description Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtr...
public TreeNode sortedArrayToBST(int[] nums) { if (nums == null || nums.length == 0) return null; return getBST(0, nums.length - 1, nums); } private TreeNode getBST(int begin, int end, int[] nums) { if (begin > end) ...
大概思路是要做一个root, 一个left subtree, right subtree. 但是我一开始只有一个function,我发现要recursion的时候, array不是很好取middle point。 因为比如最开始Array是[1,3,4,5,6,7,8,9]. 第一次mid point拿到root以后,要把middle point的左右分成两个子array 继续recursion, 类似[1,3,4,5], [7...
Given an array where elements are sorted in ascending order, convert it to a height balanced BST. For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. ...
public TreeNode sortedArrayToBST(int[] num) { if(num == null || num.length <= 0) { return null; } return createTree(0,num.length-1,num); } public TreeNode createTree(int head,int end,int [] num) { if(head > end) { return null; } int mid = (head+end)/2; TreeNode ro...