🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
~~~ package demo type Node struct { Part string //pattern string Children []*Node IsEnd bool } func NewNode() *Node { return &Node{ Part: "", //pattern: "", Children: nil, IsEnd: false, } } func (n *Node)Insert(parts []string, height int) { if len(parts) ==height { return } part := parts[height] child := n.MatchChild(part) if child == nil{ child = &Node{ Part: part, Children: nil, IsEnd: len(parts) == height +1, } n.Children = append(n.Children, child) } child.Insert(parts, height+1) } func (n *Node) MatchChild(part string) *Node { for _,child := range n.Children { if child.Part == part { return child } } return nil } ~~~ ~~~ package main import ( "example/learn/demo" "fmt" ) func main() { node := demo.NewNode() node.Insert([]string{"user"}, 0) node.Insert([]string{"user","info"}, 0) node.Insert([]string{"login","logout"}, 0) node.Insert([]string{"login","findpass"}, 0) //node.Insert([]string{"user","account"}, 0) // fmt.Println(node.MatchChild("user")) //fmt.Println(node.Children[1].Children[1]) } ~~~