构建一个时间复杂度为O(n)的目录树

 

public class TreeTest{

public static void test(Multimap<String, TestTreeBean> myMultimap,TestTreeBean bean){
// 1.获取子节点
List<TestTreeBean> childList = (List<TestTreeBean>) myMultimap.get(bean.getId());
// 2.如果子节点已经没有数据跳出循环
if(childList.size()==0){
return;
}else{
// 3.遍历子节点
for (TestTreeBean testTreeBean : childList) {
// 递归当前节点是否有子节点
test(myMultimap, testTreeBean);
}
// 4.构造子节点
bean.setBean(childList);
}

}

public static void main(String[] args) throws Exception {
Multimap<String, TestTreeBean> myMultimap = ArrayListMultimap.create();
List<TestTreeBean> list = new ArrayList<TestTreeBean>();
// 1. 创造一份模拟数据
list.add(new TestTreeBean("1", "0"));// 跟节点
list.add(new TestTreeBean("2", "1"));
list.add(new TestTreeBean("3", "1"));
list.add(new TestTreeBean("4", "2"));
list.add(new TestTreeBean("5", "2"));
list.add(new TestTreeBean("6", "3"));
// 2. 构造一个myMultimap父节点为key,myMultimap是键可以重复的数据结构,谷歌guava提供
for (TestTreeBean testTreeBean : list) {
myMultimap.put(testTreeBean.getPid(), testTreeBean);
}
// 3. 构造一个根节点,次节点可以为任意节点,为了获取此节点下的数据
TestTreeBean bean = new TestTreeBean("1", "0", null);
// 4. 递归构造目录树
test(myMultimap, bean);
System.out.println(JSON.toJSON(bean));
}
}

 

 

 

public class TestTreeBean {
private String id;

private String pid;

private List<TestTreeBean> bean;

public TestTreeBean(String id, String pid) {
super();
this.id = id;
this.pid = pid;
}

public TestTreeBean(String id, String pid, List<TestTreeBean> bean) {
super();
this.id = id;
this.pid = pid;
this.bean = bean;
}

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public String getPid() {
return pid;
}

public void setPid(String pid) {
this.pid = pid;
}

public List<TestTreeBean> getBean() {
return bean;
}

public void setBean(List<TestTreeBean> bean) {
this.bean = bean;
}

@Override
public String toString() {
return "TestTreeBean [id=" + id + ", pid=" + pid + ", bean=" + bean + "]";
}

posted on 2017-05-10 18:43  不停地朝前走  阅读(218)  评论(0编辑  收藏  举报

导航