Advertisement
crypticcoder

Trie Delete

Jun 23rd, 2017
242
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.10 KB | None | 0 0
  1.         // Complexity: O(length of key)
  2.         public boolean removeKey(String key) {
  3.             int keyLength = key.length();
  4.             TrieNode node = root;
  5.  
  6.             for(int i=0; i < keyLength; i++) {
  7.                 int value = charValue(key.charAt(i));
  8.                 if(null == node.childs[value]) return false;
  9.                 node = node.childs[value];
  10.             }
  11.  
  12.             // If the given key isn't a key
  13.             if(!node.isLeaf) return false;
  14.  
  15.             // if key node has any other child mark isLeaf == false and return
  16.             if(childCount(node) > 0) {
  17.                 node.isLeaf = false;
  18.                 return true;
  19.             }
  20.  
  21.             // Going bottom to top checking is current node has any child.
  22.             // If no child exist current node should be null
  23.             for(int i = keyLength-1; i >= 0; i--) {
  24.                 if(childCount(node) > 0) break;
  25.                 TrieNode parent = node.parent;
  26.                 parent.childs[charValue(key.charAt(i))] = null;
  27.                 node = parent;
  28.             }
  29.             return true;
  30.         }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement