problems: add „108. Convert Sorted Array to Binary Search Tree“
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
dd3b626157
commit
e11a347989
2 changed files with 34 additions and 1 deletions
|
@ -2,7 +2,7 @@
|
|||
# See https://pre-commit.com/hooks.html for more hooks
|
||||
repos:
|
||||
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||
rev: v3.2.0
|
||||
rev: v4.3.0
|
||||
hooks:
|
||||
- id: trailing-whitespace
|
||||
- id: end-of-file-fixer
|
||||
|
|
33
problems/convert-sorted-array-to-binary-search-tree.java
Normal file
33
problems/convert-sorted-array-to-binary-search-tree.java
Normal file
|
@ -0,0 +1,33 @@
|
|||
/**
|
||||
* Definition for a binary tree node.
|
||||
* public class TreeNode {
|
||||
* int val;
|
||||
* TreeNode left;
|
||||
* TreeNode right;
|
||||
* TreeNode() {}
|
||||
* TreeNode(int val) { this.val = val; }
|
||||
* TreeNode(int val, TreeNode left, TreeNode right) {
|
||||
* this.val = val;
|
||||
* this.left = left;
|
||||
* this.right = right;
|
||||
* }
|
||||
* }
|
||||
*/
|
||||
class Solution {
|
||||
private TreeNode sortedArrayToBST(int[] nums, int min, int max) {
|
||||
if (min > max) {
|
||||
return null;
|
||||
}
|
||||
|
||||
int mid = (min + max) / 2;
|
||||
return new TreeNode(
|
||||
nums[mid],
|
||||
sortedArrayToBST(nums, min, mid - 1),
|
||||
sortedArrayToBST(nums, mid + 1, max)
|
||||
);
|
||||
}
|
||||
|
||||
public TreeNode sortedArrayToBST(int[] nums) {
|
||||
return sortedArrayToBST(nums, 0, nums.length - 1);
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue