/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func sortedListToBST(head *ListNode) *TreeNode {
var nums []int
for head != nil {
nums = append(nums, head.Val)
head = head.Next
}
return helper(nums, 0, len(nums)-1)
}
func helper(nums []int, left, right int) *TreeNode {
if left > right {
return nil
}
mid := ( left + right ) / 2
root := &TreeNode{
Val:nums[mid],
}
root.Left = helper(nums, left, mid-1)
root.Right = helper(nums, mid+1, right)
return root
}