java非递归实现树形结构_java非递归组装树形结构

/**

*

* @param rootList 根结点

* @param listAll 所有结点

* @param parentId 父子集依赖关系

* @param spread有子结点是否展开

*
true 展开

*
false 不展开

* @return 树形结构的字符串

*/

public String getTreeByStack(List> rootList, List> listAll, String parentId,boolean spread){

JSONArray jsonRootList = JSONArray.fromObject(rootList);

JSONArray jsonListAll = JSONArray.fromObject(listAll);

Stack stack=new Stack();

for(int i=0;i

JSONObject root=jsonRootList.getJSONObject(i);

stack.push(root);

}

while (!stack.isEmpty()) {

JSONObject parentNode=stack.pop();

JSONArray children=new JSONArray();

for(int j=0;j

JSONObject jsonObject =jsonListAll.getJSONObject(j);

if (jsonObject.getInt(parentId)==parentNode.getInt("id")) {

children.add(jsonObject);

}

}

if (children.size()>0) {

parentNode.put("children", children);

parentNode.put("spread", spread);

JSONArray sunJsonArray=parentNode.getJSONArray("children");

for(int k=0;k

stack.push(sunJsonArray.getJSONObject(k));

}

}

}

String tree=jsonRootList.toString();

return tree;

}

你可能感兴趣的:(java非递归实现树形结构)