I need help with implementing the insert method which adds new child and siblings to the Trie. I saw many solutions. However, my problem is different because the class members insides the class are final so I can't make reference to the next element when I'm traversing the tree. I searched a lot on the internet but seems I can't find any help. I've been struggling with this for two days. I will share my code below.
Below is all I have tried with the insert method.
public class TrieChildren extends AbstractTrieChildren {
public TrieChildren(char c, AbstractTrie t, AbstractTrieChildren o) {
super(c, t, o);
}
@Override
public AbstractTrieChildren insertSorted(char character, AbstractTrie child) {
AbstractTrieChildren current = this;
AbstractTrieChildren newEntry = new TrieChildren(character, child, null);
if (current.child == null) {
current = newEntry;
}
while (current != null) {
if (current.sibling == null) {
current = newEntry;
}
current = current.sibling;
}
return current;
}
As you can see in the code below members such as sibling are final.
public abstract class AbstractTrieChildren implements Iterable<AbstractTrieChildren> {
/**
* The label of the outgoing edge.
*/
protected final char character;
/**
* The target of the outgoing edge.
*/
protected final AbstractTrie child;
/**
* The reference to the next sibling or {@code null} if none.
*/
protected final AbstractTrieChildren sibling;
public AbstractTrieChildren(char character, AbstractTrie child, AbstractTrieChildren sibling) {
this.character = character;
this.child = child;
this.sibling = sibling;
}
/**
* Adds a new labelled edge ({@link #character}, {@link #child}) to the <b>sorted</b> traversable linked list of siblings iff there is no such edge.
* If an entry already exists, then this method leaves the list unchanged.
*
* @param character the label of the possibly new labelled edge to insert
* @param child the target trie of the possibly new labelled edge to insert
* @return the new head (left-most node) of the <b>sorted</b> traversable linked sibling list
*/
public abstract AbstractTrieChildren insertSorted(char character, AbstractTrie child);
}
Any help would be appreciated. Maybe I missed something silly
question from:
https://stackoverflow.com/questions/66067163/insert-a-new-element-to-trie-when-members-are-final 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…