-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathleetcode0109.go
51 lines (41 loc) · 925 Bytes
/
leetcode0109.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/*
LeetCode 109: https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/
*/
package leetcode
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func sortedListToBST(head *ListNode) *TreeNode {
getNodeCount := func(head *ListNode) int {
count := 0
for head != nil {
count++
head = head.Next
}
return count
}
count := getNodeCount(head)
root, _ := helper109(head, 0, count-1)
return root
}
func helper109(head *ListNode, start, end int) (*TreeNode, *ListNode) {
if start > end {
return nil, head
}
if start == end {
return &TreeNode{Val: head.Val}, head.Next
}
mid := (start + end) / 2
left, head := helper109(head, start, mid-1)
root := &TreeNode{Val: head.Val}
root.Left = left
head = head.Next
right, head := helper109(head, mid+1, end)
root.Right = right
return root, head
}