java递归组装树形结构

/**
	 * 
	 * @param rootList 根结点
	 * @param listAll  全部结点
	 * @param parentId 父子组织关系依赖属性
	 * @return 返回树形字符串
	 */
	public String getTree(List<?> rootList, List<?> listAll, String parentId) {
		JSONArray jsonRootList = JSONArray.fromObject(rootList);
		JSONArray jsonListAll = JSONArray.fromObject(listAll);
		// 初始化根节点的等级
		for (int i = 0; i < jsonRootList.size(); i++) {
			jsonRootList.getJSONObject(i).put("treeLevel", 1);
		}
		getTreeChildren(jsonRootList, jsonListAll, parentId);
		return jsonRootList.toString();
	}





/***********
	 * 递归获取子节点
	 * 
	 * @param tree
	 * @param listAll
	 */
	//@Override
	private void getTreeChildren(JSONArray tree, JSONArray listAll,
			String parentId) {
		for (int i = 0; i < tree.size(); i++) {
			JSONObject node = tree.getJSONObject(i);
			JSONArray children = new JSONArray();

			for (int j = 0; j < listAll.size(); j++) {
				JSONObject jsonObject = listAll.getJSONObject(j);
				if (jsonObject.getInt(parentId) == node.getInt("id")) {//是子节点
					jsonObject.put("treeLevel", node.getInt("treeLevel") + 1);//节点等级
					children.add(jsonObject);
				}
			}
			if (children.size() > 0) {
				node.put("spread", true);// 展开子节点
				node.put("children", children);//加入子节点
				//递归获取子节点
				getTreeChildren(node.getJSONArray("children"), listAll,
						parentId);
			}

		}
相关文章
相关标签/搜索