数据库表中存放着节点信息,表结构为:id 为节点id,name为节点名字,pid为其父节点,如果pid为0则表示此节点为根节点。根据表中数据信息生成一个数对象,里面存放节点的树状信息。

代码如下:

//节点对象

public class Person {



       private String id;

   private String pid;

   private String name;



getter …

setter …    

}





// 树根对象,里面级联存储子节点信息,直到树叶

public class TreeObj {



       private String id;

   private String name;

   private List<TreeObj > cList =new ArrayList<TreeObj>();



getter …

setter …

}





public class Test {



    public static void main(String[] argStrings) {



        List<Person> pList = new ArrayList<Person>();

        pList.add(createPerson("1", "0", "a"));

        pList.add(createPerson("2", "0", "b"));

        pList.add(createPerson("3", "2", "c"));

        pList.add(createPerson("4", "2", "d"));

        pList.add(createPerson("5", "0", "e"));

        pList.add(createPerson("6", "5", "f"));

        pList.add(createPerson("7", "6", "g"));



        List<TreeObj> treeList = new ArrayList<TreeObj>();



        for (Person person : pList) {

            // find root note

            if ("0".equals(person.getPid())) {

                TreeObj treeObj = new TreeObj();

                treeObj.setId(person.getId());

                treeObj.setName(person.getName());



                treeList.add(putObjIterater(pList,treeObj));

            }

        }

        System.out.println(treeList);

    }



    private static Person createPerson(String id, String pid,String name) {

        Person p1 = new Person();

        p1.setId(id);

        p1.setPid(pid);

        p1.setName(name);

        return p1;

    }



    private static TreeObj putObjIterater(List<Person> pList, TreeObj treeObj) {

        // find child notes from pList and and the list in treeObj

        for (Person person : pList) {

            if (treeObj.getId().equals(person.getPid())) {

                // if treeObj has child note ,add it to the treeObj's list

                TreeObj newTreeObj = new TreeObj();

                newTreeObj.setId(person.getId());

                newTreeObj.setName(person.getName());

                treeObj.getCList().add(newTreeObj);

                putObjIterater(pList, newTreeObj);

            }

        }

        return treeObj;

    }



}



打印出的treeList就是我们要得到的树对象。