java - 树遍历统计总数
PHP中文网
PHP中文网 2017-04-17 17:41:43
0
1
397
{
    platformId: 3,
    areaId: "<ROOT>",
    areaName: "ROOT",
    parentAreaId: "",
    online: 0,
    offline: 0,
    total: 0,
    sum: 0,
    sumOnline: 0,
    sumOffline: 0,
    children: [{
        platformId: 3,
        areaId: "000",
        areaName: "测试",
        parentAreaId: "<ROOT>",
        online: 2,
        offline: 1,
        total: 3,
        sum: 0,
        sumOnline: 0,
        sumOffline: 0,
        children: [{
            platformId: 3,
            areaId: "000002",
            areaName: "测试2",
            parentAreaId: "000",
            online: 0,
            offline: 0,
            total: 0,
            sum: 0,
            sumOnline: 0,
            sumOffline: 0,
            children: []
        },
        {
            platformId: 3,
            areaId: "000001",
            areaName: "测试1",
            parentAreaId: "000",
            online: 30,
            offline: 0,
            total: 30,
            sum: 0,
            sumOnline: 0,
            sumOffline: 0,
            children: []
        },
        {
            platformId: 3,
            areaId: "000000",
            areaName: "测试0",
            parentAreaId: "000",
            online: 274,
            offline: 10,
            total: 284,
            sum: 0,
            sumOnline: 0,
            sumOffline: 0,
            children: []
        }
        ]
    }]
}

这种树结构的数据怎么遍历统计,每个结点的sum要是下级节点total的总和及本节点total的总和,每个节点的sumoffline要是下级节点及本节点offline的总和

 private AreaCameraStatusSum  count(AreaCameraStatusSum root){

        int total = root.getTotal();
        int offline = root.getOffline();

        if(root.getChildren().size() < 1){
            root.setSum(total);
            root.setSumOffline(offline);
            return root;
        }
        int sum = total;
        int sumOffline = offline;
       for(AreaCameraStatusSum child : root.getChildren()){
           AreaCameraStatusSum tmp = count(child);
           sum += tmp.getSum();
           sumOffline += tmp.getSumOffline();

       }
        root.setSum(sum);
        root.setSumOffline(sumOffline);

        return root;

    }

上面用递归的方法可以求出每个节点的和,不知道有没有更好的方法

PHP中文网
PHP中文网

认证高级PHP讲师

membalas semua(1)
左手右手慢动作

Anda kata ia adalah struktur pokok, kenapa tidak bina pokok dan lakukan traversal selepas pesanan....

Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan