DFS求各个公司的资产总和

DFS求各个公司的资产总和

业务描述:每个公司可能有子公司,子公司下面可能有许多部门,现在已知部门有它的账户金额,求各个公司的资产总和

如图所示:在这里插入图片描述

1.题解思路:递归求各个公司的总和,假设部门和公司可以抽象为每棵树的一个个结点,若想求每个结点的资产总和,则要求出这个节点的子节点的资产,我的思路是深度优先搜索,找到每个结点的子树,求出子树的账户金额。
2.核心思路:对于每一个结点,都要找出它的子树。
3.代码如下:

1.封装结点

import java.util.List;
public class Tree {

    Integer id;
    String name;
    Integer  parentId;
    List<Tree> children;
    Double money;

    public Tree() {
    }

    public Tree(Integer id, String name, Integer parentId, List<Tree> children,Double money) {
        this.id = id;
        this.name = name;
        this.parentId = parentId;
        this.children = children;
        this.money = money;
    }

    @Override
    public String toString() {
        return "Tree{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", parentId=" + parentId +
                ", children=" + children +
                ", money=" + money +
                '}';
    }

    public Integer getId() {
        return id;
    }

    public Double getMoney() {
        return money;
    }

    public void setMoney(Double money) {
        this.money = money;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getParentId() {
        return parentId;
    }

    public void setParentId(Integer parentId) {
        this.parentId = parentId;
    }

    public List<Tree> getChildren() {
        return children;
    }

    public void setChildren(List<Tree> children) {
        this.children = children;
    }
}

2.递归函数

  public static String transform(Tree[] tree){
        Tree head = null;
        for (int i = 0; i < tree.length; i++) {
            if (tree[i].parentId == null){       //找出头结点
                toTree(tree[i], tree);           //dfs求解
                head = tree[i];
                break;
            }
        }
        return head.toString();
    }
    public static void toTree(Tree head,Tree[] tree){
        head.children = new ArrayList<>();
        double totalMoney = head.money;
        for (int i = 0; i < tree.length; i++) {
            if (tree[i].parentId != null && tree[i].parentId == head.id){
                head.children.add(tree[i]);    //若遍历的结点是它的子孩子,则添加
                toTree(tree[i],tree);        
                totalMoney = totalMoney + tree[i].money;  //对于每一个结点,dfs汇总完当前结点的子孩子然后累加账户金额
            }
        }
        head.setMoney(totalMoney);//遍历结束,必然找到当前结点的所有子节点,然后赋值
    }
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值