import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class GTree {
private int pid;
private int id;
private String node;
private Map<Integer,GTree> child=new HashMap<Integer,GTree>();
public GTree(){}
public GTree(int pid, int id,String node) {
this.pid = pid;
this.id=id;
this.node = node;
}
public void add(GTree tree){
Integer pid=tree.getPid();
/*GTree tree1 =child.get(pid);
if(tree1==null){
child.put(pid, new GTree(0, 1, "root"));
}*/
child.put(tree.getId(), tree);
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
public void prt(){
Set<Integer> set=child.keySet();
for (Integer id : set) {
System.out.println(child.get(id));
}
}
/**
* 求某个节点上级
*/
public void getParent(int pid){
Set<Integer> set=child.keySet();
for (Integer id : set) {
if(pid==id){
System.out.println(pid+"父节点是"+child.get(id));
return;
}
}
}
/**
* 求某个节点所有上级
*/
public void getAllParent(int pid){
Set<Integer> set=child.keySet();
for (Integer id : set) {
if(pid==id){
GTree tree=child.get(id);
int _pid=tree.getPid();
if(_pid==0){
return;
}else {
System.out.println(pid+"父节点是"+child.get(_pid));
getAllParent(_pid);
}
}
}
}
private Map<Integer,GTree> getchild(){
return child;
}
/**
* 求某个节点下级
*/
public void getchild(int id){
GTree tree=child.get(id);
Map<Integer,GTree> childMap=tree.getchild();
Set<Integer> set=childMap.keySet();
for (Integer _id : set) {
System.out.println(id+"子节点是"+child.get(_id));
}
}
@Override
public String toString() {
return "GTree [pid=" + pid + ", id=" + id +
", node=" + node+"]";
}
public static void main(String[] args) {
GTree tree=new GTree();
tree.add(new GTree(0,1,"A"));
tree.add(new GTree(1,11,"A1"));
tree.add(new GTree(1,12,"A2"));
tree.add(new GTree(1,13,"A3"));
tree.add(new GTree(0,2,"B"));
tree.add(new GTree(2,14,"B1"));
tree.add(new GTree(2,15,"B2"));
tree.add(new GTree(14,141,"B21"));
// tree.prt();
// tree.getParent(14);
// tree.getAllParent(141);
tree.getchild(2);
}
}
java 树形结构
最新推荐文章于 2024-08-08 02:15:15 发布