import java.util.*;
public class TireTree {
static class Node{
private char data;
private final TreeMap<Character, Node> nextNodes = new TreeMap<>(new Comparator<Character>() {
@Override
public int compare(Character o1, Character o2) {
return o2-o1;
}
});
public Node() {
}
public Node(char data) {
this.data = data;
}
public void add(Node node){
nextNodes.put(node.getData(),node);
}
public Node getNext(char key){
return nextNodes.get(key);
}
public boolean isLeafNode(){
return nextNodes.isEmpty();
}
public char getData() {
return data;
}
public Collection<Node> getNextDescendingNodes(){
return nextNodes.values();
}
public int size() { return nextNodes.size(); }
}
private final Node root = new Node();
public TireTree() {
}
public TireTree(String... words){
for(String s:words){
this.add(s);
}
}
public void add(String s){
Node current = root;
int length = s.length();
for(int i =0;i<length;++i){
char c = s.charAt(i);
Node next = current.getNext(c);
if(next == null){
next = new Node(c);
current.add(next);
}
current = next;
}
}
public List<String> fuzzySearch(String s){
Node current = root;
StringBuilder builder;
List<String> res = new ArrayList<>();
if(s == null || "".equals(s)){
builder = new StringBuilder();
}else {
int length = s.length();
for(int i =0;i<length;++i){
current = current.getNext(s.charAt(i));
if(current == null)return null;
}
builder = new StringBuilder(s.substring(0,length-1));
}
for(String sub : traversal(current)){
res.add(builder.append(sub).toString());
builder.deleteCharAt(builder.length()-1);
}
return res;
}
private List<String> traversal(Node root) {
List<String> res = new ArrayList<>();
if (root == null || root.isLeafNode()) return res;
StringBuilder builder = new StringBuilder();
Deque<Node> pathStack = new ArrayDeque<>();
Deque<Node> stack = new ArrayDeque<>();
Map<Node, Integer> popCounter = new HashMap<>();
stack.add(root);
for(;;) {
Node current = stack.pollLast();
if(current.isLeafNode()){
builder.append(current.getData());
res.add(builder.toString());
builder.deleteCharAt(builder.length()-1);
if(stack.isEmpty())break;
Node father;
for(;;){
father = pathStack.pollLast();
popCounter.merge(father, 1, Integer::sum);
if(popCounter.get(father) != father.size()){
pathStack.add(father);
break;
}else {
builder.deleteCharAt(builder.length()-1);
}
}
}else{
stack.addAll(current.getNextDescendingNodes());
pathStack.add(current);
builder.append(current.getData());
}
}
return res;
}
}
参考链接
多叉树 最长路径 java_多叉树全路径遍历
|