java 实现递归实现tree

Posted 啊哈哈哈哈-

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 实现递归实现tree相关的知识,希望对你有一定的参考价值。

package app.util;


import java.util.ArrayList;
import java.util.List;


import com.alibaba.fastjson.JSON;


public class Menu {
private Integer pid;
private String menuName;
private Integer parentId;
private Integer position;
private List<Menu> childMenu;


public Integer getPid() {
return pid;
}

 


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

 


public String getMenuName() {
return menuName;
}

 


public void setMenuName(String menuName) {
this.menuName = menuName;
}

 


public Integer getParentId() {
return parentId;
}

 


public void setParentId(Integer parentId) {
this.parentId = parentId;
}

 


public Integer getPosition() {
return position;
}

 


public void setPosition(Integer position) {
this.position = position;
}

 


public List<Menu> getChildMenu() {
return childMenu;
}

 


public void setChildMenu(List<Menu> childMenu) {
this.childMenu = childMenu;
}

 

public Menu(Integer pid, String menuName, Integer parentId, Integer position) {
super();
this.pid = pid;
this.menuName = menuName;
this.parentId = parentId;
this.position = position;
}

 

public Menu() {
super();
}

 


public static void main(String[] args) {
List<Menu> treeMenu=new ArrayList<Menu>();

List<Menu> list=new ArrayList<Menu>();
Menu menu1=new Menu(1, "父级1", 0, 1);
Menu menu2=new Menu(2, "父级2", 0, 2);
Menu menu1_1=new Menu(3, "子级1_1", 1, 1);
Menu menu1_2=new Menu(4, "子级1_2", 1, 2);
Menu menu1_2_1=new Menu(5, "子级1_2_1", 4, 2);
list.add(menu1);
list.add(menu2);
list.add(menu1_1);
list.add(menu1_2);
list.add(menu1_2_1);

List<Menu> listTree=buildTree(list,0);

String trssJson=JSON.toJSONString(listTree);
System.out.println(trssJson);

}

public static List<Menu> buildTree(List<Menu> list,int parentId){
List<Menu> menus=new ArrayList<Menu>();
for (Menu menu : list) {

int menuId = menu.getPid();
int pid = menu.getParentId();
if (parentId == pid) {
List<Menu> menuLists = buildTree(list, menuId);

menu.setChildMenu(menuLists);
menus.add(menu);
}
}

return menus;
}
}













































































以上是关于java 实现递归实现tree的主要内容,如果未能解决你的问题,请参考以下文章

递归:python+easyui实现tree

java递归实现easyui树节点

递归改写成循环方式的实现例子-树的遍历

递归实现tree JQuery

java中树形结构怎么实现

vue---tree实现递归组件(多级下拉菜单)