Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Complexity: O(length of key)
- public boolean removeKey(String key) {
- int keyLength = key.length();
- TrieNode node = root;
- for(int i=0; i < keyLength; i++) {
- int value = charValue(key.charAt(i));
- if(null == node.childs[value]) return false;
- node = node.childs[value];
- }
- // If the given key isn't a key
- if(!node.isLeaf) return false;
- // if key node has any other child mark isLeaf == false and return
- if(childCount(node) > 0) {
- node.isLeaf = false;
- return true;
- }
- // Going bottom to top checking is current node has any child.
- // If no child exist current node should be null
- for(int i = keyLength-1; i >= 0; i--) {
- if(childCount(node) > 0) break;
- TrieNode parent = node.parent;
- parent.childs[charValue(key.charAt(i))] = null;
- node = parent;
- }
- return true;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement