今天筆試一道題,根據輸入的字符串,解析成一棵樹,並將其遍歷。
輸入樣例:-1(3(2)(5))(4(6))
以下是代碼(有什麼地方需要改進的請提出,謝謝):
package main
import (
"fmt"
"strconv"
)
type tree struct {
v *int
l *tree
r *tree
f *tree
}
func (t *tree) LCR() []int {
a := []int{}
if t.l != nil {
a = append(a,t.l.LCR()... )
}
a = append(a, *t.v)
if t.r != nil {
a = append(a,t.r.LCR()...)
}
return a
}
func main() {
a := "-1(3(2)(5))(4(6))"
l, r := 0, 0
top := &tree{}
tmp := top
for i := 0; i < len(a); i++ {
if string(a[i]) == ("(") {
r = i
if string(a[i-1]) != (")") {
n, _ := strconv.Atoi(a[l:r])
tmp.v = &n
}
l = r + 1
if tmp.l == nil {
tmp.l = &tree{f: tmp}
tmp = tmp.l
} else {
tmp.r = &tree{f: tmp}
tmp = tmp.r
}
} else if string(a[i]) == (")") {
r = i
if string(a[i-1]) != (")") {
n, _ := strconv.Atoi(a[l:r])
tmp.v = &n
}
tmp = tmp.f
}
}
b := top.LCR()
fmt.Println(b)
}