树
介绍
在树结构中,有一个根节点,这个根节点有多个子节点,每个子节点又是一颗子树的根节点,以此类推,所以树结构天然支持递归的操作。下图中A为整颗树的根节点,有以B,C为根节点的子树。
- 每个节点都只有有限个子节点或无子节点;
- 没有父节点的节点称为根节点;
- 每一个非根节点有且只有一个父节点;
- 除了根节点外,每个子节点可以分为多个不相交的子树;
- 树里面没有环路。
实现
在树节点中使用value表示节点中存放的节点值,children表示该节点的子节点数组。子节点为空表示该节点是叶子节点。
public class Tree<T> {
private T value;
private final List<Tree<T>> children;
public Tree(T value) {
this();
this.value = value;
}
public Tree() {
children = new ArrayList<>();
}
public void addChild(Tree<T> child) {
children.add(child);
}
public void removeChild(Tree<T> child) {
children.remove(child);
}
public List<Tree<T>> children() {
return children;
}
public boolean isLeaf() {
return children.isEmpty();
}
public T getValue() {
return value;
}
public void setValue(T value) {
this.value = value;
}
}
应用
查询指定前缀的单词
设计PrefixFind类,该类能够添加或删除单词,查询指定前缀的所有字符串。
添加MyCharacter类,用于存储字符及是否时单词结尾字符。
private static class MyCharacter {
// 存放的字符
char ch;
// 是否是单词的结尾
boolean isEnd;
public MyCharacter(char ch, boolean isEnd) {
this.ch = ch;
this.