677. Map Sum Pairs

class MapNode { public: MapNode() : terminate(false), value(0), children(26, nullptr) {} // constructor ~MapNode(){ for (MapNode * child : children){ if (child != nullptr) delete child; } } bool terminate; int value; vector<MapNode*> children; }; class MapSum { public: /** Initialize your data structure here. */ MapSum() { root = new MapNode(); } void insert(string key, int val) { MapNode * ptr = root; for (char k : key){ size_t pos = k - 'a'; if (ptr->children[pos] == nullptr) ptr->children[pos] = new MapNode(); ptr = ptr->children[pos]; } ptr->terminate = true; ptr->value = val; } int sum(string prefix) { int res = 0; MapNode * ptr = root; for (char c : prefix){ size_t pos = c - 'a'; if (ptr->children[pos] != nullptr) res += ptr->children[pos]->value; ptr = ptr->children[pos]; } return res; } private: MapNode * root; }; /** * Your MapSum object will be instantiated and called as such: * MapSum obj = new MapSum(); * obj.insert(key,val); * int param_2 = obj.sum(prefix); */
Mistake: still confused as pointers points to where.

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.