Skip to content

Update 108.convert-sorted-array-to-binary-search-tree.md #412

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 13, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
88 changes: 72 additions & 16 deletions problems/108.convert-sorted-array-to-binary-search-tree.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,22 +45,9 @@ https://leetcode-cn.com/problems/convert-sorted-array-to-binary-search-tree/

## 代码

代码支持:Python,JS ,Java
代码支持:JS,C++,Java,Python

Python:

```py
class Solution:
def sortedArrayToBST(self, nums: List[int]) -> TreeNode:
if not nums: return None
mid = (len(nums) - 1) // 2
root = TreeNode(nums[mid])
root.left = self.sortedArrayToBST(nums[:mid])
root.right = self.sortedArrayToBST(nums[mid + 1:])
return root
```

JS:
JS Code:

```js
var sortedArrayToBST = function (nums) {
Expand All @@ -76,14 +63,59 @@ var sortedArrayToBST = function (nums) {
};
```

Python Code:

```py
class Solution:
def sortedArrayToBST(self, nums: List[int]) -> TreeNode:
if not nums: return None
mid = (len(nums) - 1) // 2
root = TreeNode(nums[mid])
root.left = self.sortedArrayToBST(nums[:mid])
root.right = self.sortedArrayToBST(nums[mid + 1:])
return root
```



**复杂度分析**

- 时间复杂度:$O(N)$
- 空间复杂度:每次递归都 copy 了 N 的 空间,因此空间复杂度为 $O(N ^ 2)$

然而,实际上没必要开辟新的空间:

Java:
C++ Code:

```c++
class Solution {
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
return reBuild(nums, 0, nums.size()-1);
}

TreeNode* reBuild(vector<int>& nums, int left, int right)
{
// 终止条件:中序遍历为空
if(left > right)
{
return NULL;
}
// 建立当前子树的根节点
int mid = (left+right)/2;
TreeNode * root = new TreeNode(nums[mid]);

// 左子树的下层递归
root->left = reBuild(nums, left, mid-1);
// 右子树的下层递归
root->right = reBuild(nums, mid+1, right);
// 返回根节点
return root;
}
};
```

Java Code:

```java
class Solution {
Expand All @@ -105,6 +137,30 @@ class Solution {

```

Python Code:
```python
class Solution(object):
def sortedArrayToBST(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
return self.reBuild(nums, 0, len(nums)-1)

def reBuild(self, nums, left, right):
# 终止条件:
if left > right:
return
# 建立当前子树的根节点
mid = (left + right)//2
root = TreeNode(nums[mid])
# 左右子树的下层递归
root.left = self.reBuild(nums, left, mid-1)
root.right = self.reBuild(nums, mid+1, right)

return root
```

**复杂度分析**

- 时间复杂度:$O(N)$
Expand Down