# 深度优先遍历字典树(统计单词出现的个数)

Sample Input

Red Alder
Ash
Aspen
Basswood
Ash
Beech
Yellow Birch
Ash
Cherry
Cottonwood
Ash
Cypress
Red Elm
Gum
Hackberry
White Oak
Hickory
Pecan
Hard Maple
White Oak
Soft Maple
Red Oak
Red Oak
White Oak
Poplan
Sassafras
Sycamore
Black Walnut
Willow
exit

Sample Output

Ash 13.7931
Aspen 3.4483
Basswood 3.4483
Beech 3.4483
Black Walnut 3.4483
Cherry 3.4483
Cottonwood 3.4483
Cypress 3.4483
Gum 3.4483
Hackberry 3.4483
Hard Maple 3.4483
Hickory 3.4483
Pecan 3.4483
Poplan 3.4483
Red Alder 3.4483
Red Elm 3.4483
Red Oak 6.8966
Sassafras 3.4483
Soft Maple 3.4483
Sycamore 3.4483
White Oak 10.3448
Willow 3.4483
Yellow Birch 3.4483

```import java.util.Scanner;
import java.text.DecimalFormat;

class Trie{ //字典树
Trie next[] = new Trie[128];//所有儿子节点
int cnt;/* 用于记录单词出现的次数，若cnt大于0，说明
从根节点到此节点的父节点构成了一个单词，这个
单词的次数就是cnt */
public Trie(){
cnt = 0;
}
}

public class Main{
Trie root = new Trie();
String res;
int all = 0;
DecimalFormat a = new DecimalFormat("0.0000");
void solve() {
Scanner  cin = new Scanner(System.in);

String input;
while(cin.hasNext()){//用所有字符串,构造字典树
input = cin.nextLine();
// if(input.equals("exit")) break;
insert(input.toCharArray());
}
res = "";
dfs(root);//深度优先搜索字典树
}
void insert(char[] str){//将一个字符串插入字典树
int len = str.length;
int k = 0, t;
Trie p = root;
while(k!=len){
t = str[k++];
if(p.next[t] == null) p.next[t] = new Trie();
p = p.next[t];
}
p.cnt++;//字符串的最后一个节点,根节点到此节点构成了一个单词,此单词的个数加1
all++;//字符串总数加1
}

void dfs(Trie p){
if(p.cnt!=0) System.out.println(res + " " + a.format(p.cnt*100.0/all));
for(int i=0;i< 128;i++){//遍历p的所有儿子节点(邻接点)
if(p.next[i] != null){
res+=(char)i;
dfs(p.next[i]);
res = res.substring(0, res.length()-1);//恢复现场
}
}
}
public static void main(String[] args) {
Main test = new Main();
test.solve();
}
}

```

• 0

开心

• 0

板砖

• 0

感动

• 0

有用

• 0

疑问

• 0

难过

• 0

无聊

• 0

震惊