-
Notifications
You must be signed in to change notification settings - Fork 0
/
109.go
57 lines (50 loc) · 993 Bytes
/
109.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
52
53
54
55
56
57
package p109
/**
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
*/
/**
* 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
* }
*/
type ListNode struct {
Val int
Next *ListNode
}
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func sortedListToBST(head *ListNode) *TreeNode {
if head == nil {
return nil
} else if head.Next == nil {
return &TreeNode{Val: head.Val}
}
head = &ListNode{0, head}
slow, quick := head, head.Next
for quick != nil {
quick = quick.Next
if quick != nil {
slow = slow.Next
quick = quick.Next
}
}
quick = slow.Next
slow.Next = nil
node := &TreeNode{Val: quick.Val}
node.Left = sortedListToBST(head.Next)
node.Right = sortedListToBST(quick.Next)
return node
}