For notes only: Java tree statistics: each node adds the number of direct departments

Code modified from: https://blog.csdn.net/xuxingfan000/article/details/52159851
thanks @xuxingfan000

Recently, the project has encountered tree structure statistics. The depth of the tree is uncertain. The parent node = the sum of
the child nodes. This modified code needs to add the number of the parent node itself to realize the count of the parent node . For the
entity bean code, please refer to the above link
statistics demo The code is modified as follows:

package tt;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class XxfMain {

	public static List<Xmzb> allList = new ArrayList<Xmzb>();

	public static void main(String[] args) {
		Xmzb root = new Xmzb("1", "0", 0);
		Xmzb root1_1 = new Xmzb("1-1", "1", 3999);
		Xmzb root1_2 = new Xmzb("1-2", "1", 1);
		Xmzb root1_1_1 = new Xmzb("1-1-1", "1-1", 1);
		Xmzb root1_1_2 = new Xmzb("1-1-2", "1-1", 0);
		Xmzb root1_2_1 = new Xmzb("1-2-1", "1-2", 1);
		Xmzb root1_2_2 = new Xmzb("1-2-2", "1-2", 0);
		allList.add(root);
		allList.add(root1_1);
		allList.add(root1_2);
		allList.add(root1_1_1);
		allList.add(root1_1_2);
		allList.add(root1_2_1);
		allList.add(root1_2_2);
		List<Xmzb> list = new ArrayList<Xmzb>();
		list.add(root);
		doCount(root, list);
		for (Xmzb xmzb : allList) {
			System.out.println(xmzb.getId() + ":" + xmzb.getXmgs());
		}

	}

	public static Map<String, Object> doCount(Xmzb root, List<Xmzb> list) {
		// System.out.println(root.getXmgs());
		Map<String, Object> map = new HashMap<String, Object>();
		Double xmgs = 0.0;

		List<Xmzb> clist = findByQueryString(root.getId());// 此处可以使用sql通过父节点查询孩子节点sql:from
															// Xmzb where
															// year='2016' and
															// pid='"+root.getId()+"'

		// 叶子节点
		if (clist == null || clist.size() == 0) {
			if (null != root.getXmgs()) {
				map.put("xmgs", root.getXmgs());
			} else {
				map.put("xmgs", xmgs);
			}
			return map;
		}

		// 父节点
		if (clist != null && clist.size() > 0) {
			list.addAll(clist);
			for (Xmzb child : clist) {
				// 递归
				Map<String, Object> map_c = doCount(child, list);
				Double res = Double.parseDouble(map_c.get("xmgs").toString());
				child.setXmgs(res.intValue());
				// 统计当前元素的子节点个数
				xmgs += res;
			}

		}
		
		/
		//注意这两行修改//
		/
		root.setXmgs(root.getXmgs() + xmgs.intValue()); 
		map.put("xmgs", root.getXmgs());
	    /
		//注意这两行修改//
		/
		
		
		map.put("list", list);
		return map;
	}

	public static List<Xmzb> findByQueryString(String pid) {
		List<Xmzb> list = new ArrayList<Xmzb>();
		for (Xmzb xmzb : allList) {
			if (xmzb.getPid().equals(pid)) {
				list.add(xmzb);
			}
		}
		return list;

	}

}

The results are as follows
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_35977139/article/details/97375252