package main
import"fmt"type Tree struct{
pass int
end int
edges map[byte]*Tree
}var root *Tree
func(p *Tree)InsertString(str string){
cur := p
cur.pass++for_, ch :=range str {if value, ok := cur.edges[byte(ch)]; ok {
cur = value
cur.pass++}else{
cur.edges[byte(ch)]=&Tree{1,0,make(map[byte]*Tree)}
cur = cur.edges[byte(ch)]}}
cur.end++}func(p *Tree)SearchString(str string)bool{
cur := p
for_, ch :=range str {if value, ok := cur.edges[byte(ch)]; ok {
cur = value
}else{returnfalse}}returntrue}funcDisplay(root *Tree){for k, value :=range root.edges {
fmt.Println(string(k), value.pass, value.end)Display(value)}}funcmain(){
strs :=make([]string,0,10)
strs =append(strs,"abc","ab","abcd","abuy")
root =&Tree{0,0,make(map[byte]*Tree)}for_, str :=range strs {
root.InsertString(str)}Display(root)}
c++代码
#include<iostream>#include<unordered_map>structNode{int pass;// 有几个经过该Nodeint end;// 是否以这个为结尾
std::unordered_map<char,Node*>edges;// 边表示字符Node(int pass,int end):pass(pass),end(end){}};classTree{private:
Node* root;voidPrintTree(Node* root){for(auto it = root->edges.begin(); it != root->edges.end();++it){
std::cout<<it->first<<' '<<it->second->pass<<' '<<it->second->end<<std::endl;PrintTree(it->second);}}public:Tree():root(newNode(0,0)){}voidInsertString(std::string str){
Node* cur = root;++cur->pass;for(int i =0; i < str.size();++i){if(cur->edges.find(str[i])!= cur->edges.end()){
cur = cur->edges[str[i]];++cur->pass;}else{
cur->edges[str[i]]=newNode(1,0);
cur = cur->edges[str[i]];}}++cur->end;
cur =nullptr;}boolSearchString(std::string str){
Node * cur = root;for(char ch : str){if(cur->edges.find(ch)!= cur->edges.end()){
cur = cur->edges[ch];}else{returnfalse;}}returntrue;}voidDisplayTree(){this->PrintTree(root);}};intmain(){
std::string strs[]={"abc","abcd","ab","adryu"};
Tree test;for(auto str : strs){
test.InsertString(str);}
test.DisplayTree();
std::getchar();return0;}