Skip to content

Commit 2461254

Browse files
committed
[LeetCode Sync] Runtime - 3 ms (70.62%), Memory - 19.1 MB (59.86%)
1 parent 1706922 commit 2461254

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
<p>Given an integer array <code>nums</code> where the elements are sorted in <strong>ascending order</strong>, convert <em>it to a </em><span data-keyword="height-balanced"><strong><em>height-balanced</em></strong></span> <em>binary search tree</em>.</p>
2+
3+
<p>&nbsp;</p>
4+
<p><strong class="example">Example 1:</strong></p>
5+
<img alt="" src="https://assets.leetcode.com/uploads/2021/02/18/btree1.jpg" style="width: 302px; height: 222px;" />
6+
<pre>
7+
<strong>Input:</strong> nums = [-10,-3,0,5,9]
8+
<strong>Output:</strong> [0,-3,9,-10,null,5]
9+
<strong>Explanation:</strong> [0,-10,5,null,-3,null,9] is also accepted:
10+
<img alt="" src="https://assets.leetcode.com/uploads/2021/02/18/btree2.jpg" style="width: 302px; height: 222px;" />
11+
</pre>
12+
13+
<p><strong class="example">Example 2:</strong></p>
14+
<img alt="" src="https://assets.leetcode.com/uploads/2021/02/18/btree.jpg" style="width: 342px; height: 142px;" />
15+
<pre>
16+
<strong>Input:</strong> nums = [1,3]
17+
<strong>Output:</strong> [3,1]
18+
<strong>Explanation:</strong> [1,null,3] and [3,1] are both height-balanced BSTs.
19+
</pre>
20+
21+
<p>&nbsp;</p>
22+
<p><strong>Constraints:</strong></p>
23+
24+
<ul>
25+
<li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li>
26+
<li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>
27+
<li><code>nums</code> is sorted in a <strong>strictly increasing</strong> order.</li>
28+
</ul>
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
# Definition for a binary tree node.
2+
# class TreeNode:
3+
# def __init__(self, val=0, left=None, right=None):
4+
# self.val = val
5+
# self.left = left
6+
# self.right = right
7+
class Solution:
8+
def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
9+
def dfs(left: int, right: int) -> Optional[TreeNode]:
10+
if left > right:
11+
return None
12+
mid = (left + right) // 2
13+
return TreeNode(nums[mid], dfs(left, mid - 1), dfs(mid + 1, right))
14+
15+
return dfs(0, len(nums) - 1)

0 commit comments

Comments
 (0)