java递归构建菜单树

 1 package testSimple;
 2 
 3 import java.util.ArrayList;
 4 import java.util.List;
 5 
 6 public class BuildTree {
 7     public static void main(String[] args) {
 8         List<Tree> list = new ArrayList<Tree>();
 9         list.add(new Tree(1, "一级菜单", 0));
10         list.add(new Tree(2, "二级菜单1", 1));
11         list.add(new Tree(3, "二级菜单2", 1));
12         list.add(new Tree(4, "二级菜单3", 1));
13         list.add(new Tree(5, "三级菜单11", 2));
14         list.add(new Tree(6, "三级菜单12", 2));
15         list.add(new Tree(7, "三级菜单21", 3));
16         list.add(new Tree(8, "三级菜单22", 3));
17         list.add(new Tree(9, "三级菜单31", 4));
18         list.add(new Tree(10, "三级菜单32", 4));
19 
20         List<Tree> result = buildTree(list, 0);
21         System.out.println(result);
22     }
23 
24     public static List<Tree> buildTree(List<Tree> list, int fid) {
25         List<Tree> resultList = new ArrayList<Tree>();
26         if (list == null || list.size() == 0 || fid < 0) {
27             return null;
28         }
29         for (Tree tree : list) {
30             if (tree.getFid() == fid) {
31                 resultList.add(tree);
32                 tree.setChildren(buildTree(list, tree.getId()));
33             }
34         }
35         return resultList;
36     }
37 
38 }
39 
40 class Tree {
41     private int id;
42     private String name;
43     private int fid;
44     private List<Tree> children;
45 
46     public Tree(int id, String name, int fid) {
47         super();
48         this.id = id;
49         this.name = name;
50         this.fid = fid;
51     }
52 
53     public int getId() {
54         return id;
55     }
56 
57     public void setId(int id) {
58         this.id = id;
59     }
60 
61     public String getName() {
62         return name;
63     }
64 
65     public void setName(String name) {
66         this.name = name;
67     }
68 
69     public int getFid() {
70         return fid;
71     }
72 
73     public void setFid(int fid) {
74         this.fid = fid;
75     }
76 
77     public List<Tree> getChildren() {
78         return children;
79     }
80 
81     public void setChildren(List<Tree> children) {
82         this.children = children;
83     }
84 
85 }

 

posted @ 2017-08-08 18:19  chenxiangxiang  阅读(2041)  评论(0编辑  收藏  举报