手写一个树
import java.util.ArrayList; public class shu { static class node { public String s; //存储数据 public ArrayList<node> list; //创建一个共工的集合 public node (String s) { list = new ArrayList<node>(); this.s = s; //将传入的数据赋给本类中的s } } public static void main(String[] args) { // TODO Auto-generated method stub node root = chuangjianshu(); dfs(root); } public static void dfs(node root) { System.out.println(root.s); //输出本次的根结点 for(int i = 0; i < root.list.size(); i++) { node ss = root.list.get(i); dfs(ss); } } public static node chuangjianshu() { node root = new node("我的垃圾电脑"); //设置根结点 //和跟root连接的 node a1 = new node("C盘"); //设置根节点的其他子节点 node a2 = new node("D盘"); //根C盘连接的 node b1 = new node("c1"); //设置C盘的子节点 node b2 = new node("c2"); node b3 = new node("c3"); node b4 = new node("c4"); node c1 = new node("d1"); //根D盘连接的 node c2 = new node("d2"); node c3 = new node("d3"); node c4 = new node("d4"); root.list.add(a1); //和根结点连接 root.list.add(a2); a2.list.add(c1); //和c盘连接 a2.list.add(c2); a2.list.add(c3); a2.list.add(c4); a1.list.add(b1); //和d盘连接 a1.list.add(b2); a1.list.add(b3); a1.list.add(b4); return root; //每次返回本次的根结点,从这个根节点再次向下 } }