LeetCode677. 键值映射(相关话题:Trie前缀树)

分析:在这个案例中,Trie是作为一种映射来使用(在Node节点中存储了一个value值)。

集合和映射的关系:映射本身就是把集合中的每一个元素当做一个键,每一键绑定一个value,绑定体现在Node中。

 1 import java.util.TreeMap;
 2 class MapSum {
 3 
 4     private class Node{
 5         public int value;
 6         public TreeMap<Character, Node> next;
 7         public Node(int value){
 8             this.value = value;
 9             next = new TreeMap<>();
10         }
11         public Node(){
12             this(0);
13         }
14     }
15     private Node root;
16     /** Initialize your data structure here. */
17     public MapSum() {
18         root = new Node();
19 
20     }
21     
22     public void insert(String key, int val) {
23         Node cur = root;
24         for(int i = 0; i < key.length(); i++){
25             char c = key.charAt(i);
26             if(cur.next.get(c) == null){
27                 cur.next.put(c, new Node());
28             }
29             cur = cur.next.get(c);
30         }
31         cur.value = val;
32     }
33     
34     public int sum(String prefix) {
35         Node cur = root;
36         for(int i = 0; i < prefix.length(); i++){
37             char c = prefix.charAt(i);
38             if(cur.next.get(c) == null){
39                 return 0;
40             }
41             cur = cur.next.get(c);
42         }
43         return sum(cur); // 以cur作为根结点进行遍历
44     }
45     // 遍历node以及node所有的子树,将所有节点的value值加起来。
46     private int sum(Node node){
47         // 显示指出(可以注释掉)递归到底的情况——当前节点是叶子节点,即下一个节点的映射大小为0,也就是没有下一个节点
48         // if(node.next.size() == 0){
49         //     return node.value;
50         // }
51         int res = node.value;
52         // node可以指向的所有下一个字符相应的节点   (如果是叶子节点循环的遍历不会执行,相当于直接return node.value)
53         for(char c : node.next.keySet()){
54             res += sum(node.next.get(c)); //递归,以这个节点为根的sum值
55         }
56         return res;
57     }
58 }
59 
60 /**
61  * Your MapSum object will be instantiated and called as such:
62  * MapSum obj = new MapSum();
63  * obj.insert(key,val);
64  * int param_2 = obj.sum(prefix);
65  */
Solution bobo
原文地址:https://www.cnblogs.com/HuangYJ/p/12862819.html