public: char data; int val; bool leaf; map<char,Node> next;
Node(char c){ data = c; leaf = false; }
Node(){};
};
classMapSum { public: Node root;
/** Initialize your data structure here. */ MapSum() { root = Node(); } voidinsert(string key, int val){ Node *trie = &root; int i =0,n = key.size(); char c; while(i < n){ c = key[i]; if(!trie->next.count(c)){ trie->next[c] = Node(c); } trie = &trie->next[c]; i++; } trie->val = val; trie->leaf = true; } // 递归求和 inttrave(Node *trie){ int ans = 0; if(trie->leaf) {ans += trie->val;} for(auto &p:trie->next){ Node *t = &(p.second); ans += trave(t); } return ans; } intsum(string prefix){ Node *trie = &root; int ans = 0; int i =0, n = prefix.size(); char c; while( i < n){ c = prefix[i]; if(!trie->next.count(c)) return0; trie = &trie->next[c]; i++; } returntrave(trie); } };
/** * Your MapSum object will be instantiated and called as such: * MapSum* obj = new MapSum(); * obj->insert(key,val); * int param_2 = obj->sum(prefix); */