-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
67 lines (57 loc) · 982 Bytes
/
main.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
58
59
60
61
62
63
64
65
66
67
package main
import (
"fmt"
)
func main() {
fmt.Println("Hello world")
}
type ListNode struct {
Val int
Next *ListNode
}
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func sortedListToBST(head *ListNode) *TreeNode {
var runner func(head *ListNode)
var result *TreeNode
runner = func(node *ListNode) {
if node == nil {
return
}
if node.Next == nil {
result = insert(result, node.Val)
return
}
var prev *ListNode
fast, slow := node, node
for fast != nil && fast.Next != nil {
fast = fast.Next.Next
prev = slow
slow = slow.Next
}
if prev != nil {
prev.Next = nil
}
result = insert(result, slow.Val)
runner(node)
runner(slow.Next)
}
runner(head)
return result
}
func insert(root *TreeNode, val int) *TreeNode {
if root == nil {
return &TreeNode{
Val: val,
}
}
if root.Val > val {
root.Left = insert(root.Left, val)
} else {
root.Right = insert(root.Right, val)
}
return root
}