28 lines
646 B
Go
28 lines
646 B
Go
package top100liked
|
|
|
|
// https://leetcode.cn/problems/convert-sorted-array-to-binary-search-tree/description/?envType=study-plan-v2&envId=top-100-liked
|
|
|
|
type TreeNode struct {
|
|
Val int
|
|
Left *TreeNode
|
|
Right *TreeNode
|
|
}
|
|
|
|
func sortedArrayToBST(nums []int) *TreeNode {
|
|
if len(nums) == 0 {
|
|
return nil
|
|
}
|
|
if len(nums) == 1 {
|
|
return &TreeNode{Val: nums[0]}
|
|
}
|
|
if len(nums) == 2 {
|
|
return &TreeNode{Val: nums[1], Left: &TreeNode{Val: nums[0]}}
|
|
}
|
|
rootIdx := len(nums) / 2
|
|
rootVal := nums[rootIdx]
|
|
root := &TreeNode{Val: rootVal}
|
|
root.Left = sortedArrayToBST(nums[:rootIdx])
|
|
root.Right = sortedArrayToBST(nums[rootIdx+1:])
|
|
return root
|
|
}
|