You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

147 lines
3.1 KiB

package com.fr.plugin.event.manager.data;
import java.util.LinkedList;
import java.util.List;
/**
* 自定义的树,用来存放数据
* @author Joe
* Created by Joe on 12/14/2020
*/
public class MyTree {
// 树节点
private MyNode data;
// 父节点,根没有父节点
private MyTree parent;
// 子节点,叶子节点没有子节点
private List<MyTree> children;
// 保存了当前节点及其所有子节点,方便查询
private List<MyTree> elementsIndex;
public MyTree() {
this(new MyNode());
}
public MyTree(MyNode data) {
this.data = data;
this.children = new LinkedList<>();
this.elementsIndex = new LinkedList<>();
this.elementsIndex.add(this);
}
public MyNode getData() {
return data;
}
public void setData(MyNode data) {
this.data = data;
}
public List<MyTree> getChildren() {
return children;
}
public List<MyTree> getElementsIndex() {
return elementsIndex;
}
/**
* 判断是否为根:根没有父节点
* @return
*/
public boolean isRoot() {
return parent == null;
}
/**
* 判断是否为叶子节点:子节点没有子节点
* @return
*/
public boolean isLeaf() {
return children.size() == 0;
}
/**
* 添加一个子节点
* @param child 子树
*/
public void addChild(MyTree child) {
child.parent = this;
this.children.add(child);
this.registerChildForSearch(child);
}
/**
* 添加一个子节点
* @param child 子树的节点
* @return 子树
*/
public MyTree addChild(MyNode child) {
MyTree childNode = new MyTree(child);
childNode.parent = this;
this.children.add(childNode);
this.registerChildForSearch(childNode);
return childNode;
}
/**
* 删除一个子树
*
* @param child 子树
*/
public void removeChild(MyTree child) {
// 如果是根的话,就保留
if (child.parent != null) {
child.parent.children.remove(child);
child.parent = null;
}
}
/**
* 递归为当前节点以及当前节点的所有父节点增加新的节点
* @param node
*/
private void registerChildForSearch(MyTree node) {
elementsIndex.add(node);
if (parent != null) {
parent.registerChildForSearch(node);
}
}
/**
* 获取子树
* @param index 序号
* @return 子树
*/
public MyTree findChild(int index) {
return children.get(index);
}
/**
* 获取子树大小
* @return 子树大小
*/
public int getChildrenSize() {
return children.size();
}
/**
* 根据子树对象获取它的序号
* @param child
* @return
*/
public int getIndexOfChild(Object child) {
int count = getChildrenSize();
for (int i = 0; i < count; i++) {
MyTree comp = findChild(i);
if (comp == child) {
return i;
}
}
return -1;
}
}