3.6 树的递归应用

在一个公司结构中

  1. 每个人都有一个快乐值,最小为 0, 最大为 100
  2. 每个人都只有一个领导,最高层没有领导
  3. 现在要举办一个聚会,上级到,下级就不能来
    求出聚会的最大快乐值
class TreeNode {
	// 下级员工
    public List<TreeNode> children;
    // 快乐值
    public int value;

    public TreeNode(Integer value) {
        this.value = value;
        this.children = new ArrayList<>();
    }
}
	// 暴力递归
    public int maxHappyCompare(TreeNode treeNode) {
        int m1 = maxHappyCompare(treeNode, true);
        int m2 = maxHappyCompare(treeNode, false);
        return Math.max(m1, m2);
    }

    public int maxHappyCompare(TreeNode treeNode, boolean include) {
        if (treeNode == null) {
            return 0;
        }
        int max = 0;
        if (include) {
            for (TreeNode employee : treeNode.children) {
                max = Math.max(max, maxHappyCompare(employee, false));
            }
            max += treeNode.value;
        } else {
            for (TreeNode node : treeNode.children) {
                max = Math.max(max, maxHappyCompare(node, true));
                max = Math.max(max, maxHappyCompare(node, false));
            }
        }
        return max;
    }

    class Info8 {
        public int yes;
        public int no;

        public Info8(int yes, int no) {
            this.yes = yes;
            this.no = no;
        }
    }
	// 向子树要信息
    public int maxHappy(TreeNode node) {
        Info8 info = processMaxHappy(node);
        return Math.max(info.yes, info.no);
    }

    private Info8 processMaxHappy(TreeNode node) {
        if (node == null) {
            return new Info8(0, 0);
        }
        int yes = 0, no = 0;
        for (TreeNode child : node.children) {
            Info8 i1 = processMaxHappy(child);
            yes = Math.max(yes, i1.no);
            no = Math.max(no, Math.max(i1.yes, i1.no));
        }
        return new Info8(yes + node.value, no);
    }

    @Test
    public void test2() {
        for (int i = 0; i < 10000; i++) {
            TreeNode node = Reduce.treeNode(10, 0, 100);
            int r1 = maxHappy(node);
            int r2 = maxHappyCompare(node);
            if (r1 != r2) {
                System.out.println(node);
                r1 = maxHappy(node);
                r2 = maxHappyCompare(node);
                return;
            }
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值