java非递归组装树形结构

/**
	  * 
	  * @param rootList 根结点
	  * @param listAll  全部结点
	  * @param parentId  父子集依赖关系
	  * @param spread	有子结点是否展开
	  * <br>    true  展开
	  * <br>    false 不展开
	  * @return 树形结构的字符串
	  */
public String getTreeByStack(List<?> rootList, List<?> listAll, String parentId,boolean spread){
		JSONArray jsonRootList = JSONArray.fromObject(rootList);
		JSONArray jsonListAll = JSONArray.fromObject(listAll);
		Stack<JSONObject> stack=new Stack<JSONObject>();
		for(int i=0;i<jsonRootList.size();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<jsonListAll.size();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<sunJsonArray.size();k++){
					stack.push(sunJsonArray.getJSONObject(k));
				}
			}
		}
		String tree=jsonRootList.toString();
		return tree;
	}