commit 2b8100e7a0ee9cc3eb85bb6b274641ecba279a31 parent 9989dcdfc9e49db9afa0fb26b499a1c1226876fd Author: AndrewLockVI <andrewlaack1@gmail.com> Date: Thu, 4 May 2023 12:41:04 -0500 Completed convert sorted array to binary tree using dart Diffstat:
| A | convert-sorted-array-to-binary-search-tree/convert-sorted-array-to-binary-search-tree.dart | | | 19 | +++++++++++++++++++ |
1 file changed, 19 insertions(+), 0 deletions(-)
diff --git a/convert-sorted-array-to-binary-search-tree/convert-sorted-array-to-binary-search-tree.dart b/convert-sorted-array-to-binary-search-tree/convert-sorted-array-to-binary-search-tree.dart @@ -0,0 +1,19 @@ +//Take an input list called nums and convert it to a binary search tree. +//The time complexity of this is O(n) where n is the number of values in the list. +//Time: 257ms Beats: 71.43% +//Memory: 143.6MB Beats: 57.14% +class Solution { + TreeNode? sortedArrayToBST(List<int> nums) { + if(nums.isEmpty){ + return null; + } + TreeNode root = new TreeNode(); + int mid = (nums.length / 2).toInt(); + root.val = nums[mid]; + TreeNode? left = sortedArrayToBST(nums.sublist(0 , mid)); + TreeNode? right = sortedArrayToBST(nums.sublist(mid + 1)); + root.left = left; + root.right = right; + return root; + } +}