From 9d2268e87184294fb0ea1671a8fec37803688c05 Mon Sep 17 00:00:00 2001 From: pro100ton Date: Wed, 5 Mar 2025 23:50:11 +0300 Subject: [PATCH] Add solution for leetcode 108 task --- .../108_convert_sorted_array_to_bst/go.mod | 3 ++ .../108_convert_sorted_array_to_bst/main.go | 50 +++++++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 leetcode/binary_trees/108_convert_sorted_array_to_bst/go.mod create mode 100644 leetcode/binary_trees/108_convert_sorted_array_to_bst/main.go diff --git a/leetcode/binary_trees/108_convert_sorted_array_to_bst/go.mod b/leetcode/binary_trees/108_convert_sorted_array_to_bst/go.mod new file mode 100644 index 0000000..3f887e5 --- /dev/null +++ b/leetcode/binary_trees/108_convert_sorted_array_to_bst/go.mod @@ -0,0 +1,3 @@ +module BST_108 + +go 1.21.3 diff --git a/leetcode/binary_trees/108_convert_sorted_array_to_bst/main.go b/leetcode/binary_trees/108_convert_sorted_array_to_bst/main.go new file mode 100644 index 0000000..00c2a94 --- /dev/null +++ b/leetcode/binary_trees/108_convert_sorted_array_to_bst/main.go @@ -0,0 +1,50 @@ +package main + +import "fmt" + +/** +Given an integer array nums where the elements are sorted in ascending order, convert it to a +height-balanced binary search tree. + +Constraints: + +1 <= nums.length <= 104 +-104 <= nums[i] <= 104 +nums is sorted in a strictly increasing order. + +**/ + +type TreeNode struct { + Val int + Left *TreeNode + Right *TreeNode +} + +func sortedArrayToBST(nums []int) *TreeNode { + if len(nums) == 0 { + return nil + } + return buildBST(nums, 0, len(nums)-1) +} + +func buildBST(nums []int, left, right int) *TreeNode { + if left > right { + return nil + } + + // Find the middle element and make it the root + mid := (left + right) / 2 + root := &TreeNode{Val: nums[mid]} + + // Recursively build the left and right subtrees + root.Left = buildBST(nums, left, mid-1) + root.Right = buildBST(nums, mid+1, right) + + return root +} + +func main() { + nums := []int{2, 3, 4, 5, 6} + result := sortedArrayToBST(nums) + fmt.Printf("%v, left val: %v, right val: %v", result.Val, result.Left.Val, result.Right.Val) +}