-
Notifications
You must be signed in to change notification settings - Fork 0
/
1028.recover-a-tree-from-preorder-traversal.go
76 lines (72 loc) · 1.27 KB
/
1028.recover-a-tree-from-preorder-traversal.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
68
69
70
71
72
73
74
75
76
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
// 12 ms, faster than 95.92%
func recoverFromPreorder(S string) *TreeNode {
nodes := [][]int{} // [depth,val]
for i := 0; i < len(S); {
dep := 0
for i < len(S) && S[i] == '-' {
dep++
i++
}
node := []int{dep, 0}
l := i
for i < len(S) && S[i] != '-' {
i++
}
node[1], _ = strconv.Atoi(S[l:i])
nodes = append(nodes, node)
}
return pre(nodes)
}
//
func pre(nodes [][]int) *TreeNode {
if len(nodes) == 0 {
return nil
}
if len(nodes) == 1 {
return &TreeNode{nodes[0][1], nil, nil}
}
root := &TreeNode{}
root.Val = nodes[0][1]
dep := nodes[0][0]
if nodes[1][0] == nodes[0][0]+1 {
// 找 dep+1 切分两块
i := 2
for ; i < len(nodes); i++ {
if nodes[i][0] == dep+1 {
break
}
}
if i == len(nodes) {
// 右子树为nil
root.Right = nil
} else {
root.Right = pre(nodes[i:])
}
root.Left = pre(nodes[1:i])
} else {
// 左子树为nil
root.Left = nil
// 找 dep+1 切分两块
i := 2
for ; i < len(nodes); i++ {
if nodes[i][0] == dep+1 {
break
}
}
if i == len(nodes) {
// 右子树为nil
root.Right = nil
} else {
root.Right = pre(nodes[i:])
}
}
return root
}