From e11a347989226b8825aa8c2bc7982bf201591d3f Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Wed, 10 Aug 2022 20:58:57 +0200 Subject: [PATCH] =?UTF-8?q?problems:=20add=20=E2=80=9E108.=20Convert=20Sor?= =?UTF-8?q?ted=20Array=20to=20Binary=20Search=20Tree=E2=80=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- .pre-commit-config.yaml | 2 +- ...rt-sorted-array-to-binary-search-tree.java | 33 +++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 problems/convert-sorted-array-to-binary-search-tree.java diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index fd16ba2..ca7e465 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -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 diff --git a/problems/convert-sorted-array-to-binary-search-tree.java b/problems/convert-sorted-array-to-binary-search-tree.java new file mode 100644 index 0000000..f24851c --- /dev/null +++ b/problems/convert-sorted-array-to-binary-search-tree.java @@ -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); + } +}