Add solution for leetcode 108 task
This commit is contained in:
parent
df759315e2
commit
9d2268e871
2 changed files with 53 additions and 0 deletions
|
@ -0,0 +1,3 @@
|
|||
module BST_108
|
||||
|
||||
go 1.21.3
|
|
@ -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)
|
||||
}
|
Loading…
Reference in a new issue