-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinarytree.go
More file actions
101 lines (89 loc) · 1.72 KB
/
binarytree.go
File metadata and controls
101 lines (89 loc) · 1.72 KB
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package leetcodeutil
import (
"fmt"
"regexp"
"strconv"
"strings"
)
// TreeNode struct
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
const treeNodePat = "(-?[0-9]+|null)"
var binarytreeInputPat = regexp.MustCompile(`^\[(` + treeNodePat + `((,` + treeNodePat + `)+)?)?\]$`)
// BinaryTree generates *TreeNode
func BinaryTree(input string) *TreeNode {
if !binarytreeInputPat.MatchString(input) {
panic("invalid input")
}
input = strings.TrimLeft(input, "[")
input = strings.TrimRight(input, "]")
if len(input) == 0 {
return nil
}
vals := strings.Split(input, ",")
dummyRoot := &TreeNode{}
queue := []*TreeNode{dummyRoot}
for i, val := range vals {
node := queue[0]
if i%2 == 0 {
queue = queue[1:]
}
if val == "null" {
continue
}
n, _ := strconv.Atoi(val)
child := &TreeNode{Val: n}
if i%2 != 0 {
node.Left = child
} else {
node.Right = child
}
queue = append(queue, child)
}
return dummyRoot.Right
}
func (t *TreeNode) String() string {
if t == nil {
return "[]"
}
vals := []string{}
dummyRoot := &TreeNode{Right: t}
queue := []*TreeNode{dummyRoot}
notNilCnt := 1
for len(queue) > 0 {
node := queue[0]
queue = queue[1:]
if node != nil {
notNilCnt--
}
vals = append(vals, node.toStr())
if node == nil {
continue
}
if node.Left != nil {
notNilCnt++
}
if node.Right != nil {
notNilCnt++
}
if notNilCnt == 0 {
break
}
queue = append(queue, node.Left)
queue = append(queue, node.Right)
}
return "[" + strings.Join(vals[2:], ",") + "]"
}
func (t *TreeNode) toStr() string {
if t == nil {
return "null"
}
return strconv.Itoa(t.Val)
}
// Print outputs *TreeNode.String()
func (t *TreeNode) Print() {
fmt.Println(t)
}