mirror of
https://github.moeyy.xyz/https://github.com/trekhleb/javascript-algorithms.git
synced 2024-12-25 22:46:20 +08:00
Simplify deletion method of TrieNode.
This commit is contained in:
parent
a7ffba157c
commit
4104155182
@ -42,20 +42,16 @@ export default class TrieNode {
|
||||
* @return {TrieNode}
|
||||
*/
|
||||
removeChild(character) {
|
||||
function isSafeToDelete(node) {
|
||||
return (
|
||||
node
|
||||
&& !node.isCompleteWord
|
||||
&& node.children.getKeys().length === 0
|
||||
);
|
||||
}
|
||||
|
||||
const childNode = this.getChild(character);
|
||||
|
||||
// delete childNode only if:
|
||||
// - childNode has NO children
|
||||
// - childNode.isCompleteWord === false
|
||||
if (isSafeToDelete(childNode)) {
|
||||
// Delete childNode only if:
|
||||
// - childNode has NO children,
|
||||
// - childNode.isCompleteWord === false.
|
||||
if (
|
||||
childNode
|
||||
&& !childNode.isCompleteWord
|
||||
&& !childNode.hasChildren()
|
||||
) {
|
||||
this.children.delete(character);
|
||||
}
|
||||
|
||||
@ -70,6 +66,14 @@ export default class TrieNode {
|
||||
return this.children.has(character);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether current TrieNode has children or not.
|
||||
* @return {boolean}
|
||||
*/
|
||||
hasChildren() {
|
||||
return this.children.getKeys().length !== 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return {string[]}
|
||||
*/
|
||||
|
@ -30,6 +30,16 @@ describe('TrieNode', () => {
|
||||
expect(trieNode.getChild('b')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should check if node has children', () => {
|
||||
const trieNode = new TrieNode('c');
|
||||
|
||||
expect(trieNode.hasChildren()).toBe(false);
|
||||
|
||||
trieNode.addChild('a');
|
||||
|
||||
expect(trieNode.hasChildren()).toBe(true);
|
||||
});
|
||||
|
||||
it('should check if node has specific child', () => {
|
||||
const trieNode = new TrieNode('c');
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user