mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 02:53:31 +08:00
Merge pull request #109 from Joshua-Lu/patch-26
更新 0108.将有序数组转换为二叉搜索树 Java版本
This commit is contained in:
@ -209,27 +209,28 @@ public:
|
||||
|
||||
|
||||
Java:
|
||||
```java
|
||||
```Java
|
||||
class Solution {
|
||||
public TreeNode sortedArrayToBST(int[] nums) {
|
||||
return sortArr(nums,0,nums.length);
|
||||
return sortedArrayToBST(nums, 0, nums.length);
|
||||
}
|
||||
|
||||
private TreeNode sortArr(int[] nums, int lo, int hi) {
|
||||
if (lo == hi) return null;
|
||||
int rootIdx = (lo + hi)/2;
|
||||
|
||||
int rootValue = nums[rootIdx];
|
||||
TreeNode root = new TreeNode(rootValue);
|
||||
|
||||
root.left = sortArr(nums,lo,rootIdx);
|
||||
root.right = sortArr(nums,rootIdx+1,hi);
|
||||
|
||||
public TreeNode sortedArrayToBST(int[] nums, int left, int right) {
|
||||
if (left >= right) {
|
||||
return null;
|
||||
}
|
||||
if (right - left == 1) {
|
||||
return new TreeNode(nums[left]);
|
||||
}
|
||||
int mid = left + (right - left) / 2;
|
||||
TreeNode root = new TreeNode(nums[mid]);
|
||||
root.left = sortedArrayToBST(nums, left, mid);
|
||||
root.right = sortedArrayToBST(nums, mid + 1, right);
|
||||
return root;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```
|
||||
|
||||
Python:
|
||||
|
||||
|
Reference in New Issue
Block a user