-
Notifications
You must be signed in to change notification settings - Fork 0
/
prob0109.go
61 lines (52 loc) · 1.02 KB
/
prob0109.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
package prob0109
import "fmt"
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
}
middlePreNode, middleNode := findMiddleNode(head)
if middlePreNode != nil {
middlePreNode.Next = nil
} else {
head = nil
}
middleNextNode := middleNode.Next
middleNode.Next = nil
treeNode := &TreeNode{
Val: middleNode.Val,
}
// TODO: delete
fmt.Println(treeNode.Val)
treeNode.Left = sortedListToBST(head)
treeNode.Right = sortedListToBST(middleNextNode)
return treeNode
}
func findMiddleNode(head *ListNode) (*ListNode, *ListNode) {
l := 0
tem := head
for tem != nil {
l++
tem = tem.Next
}
middleNodePos := l / 2
middlePreNodePos := middleNodePos - 1
var middleNode, middlePreNode *ListNode
tem = head
for i := 0; i < middleNodePos; i++ {
if i == middlePreNodePos {
middlePreNode = tem
}
tem = tem.Next
}
middleNode = tem
return middlePreNode, middleNode
}