leetcode 337.House Robber III (房屋强盗3)

The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the “root.” Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that “all houses in this place forms a binary tree”. It will automatically contact the police if two directly-linked houses were broken into on the same night.

Determine the maximum amount of money the thief can rob tonight without alerting the police.

Example 1:

Input: [3,2,3,null,3,null,1]

     3
    / \
   2   3
    \   \ 
     3   1

Output: 7
Explanation: Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.

房间的布局组成一个二叉树,而robber不能同时抢相连的parent和child的房间,问能抢到的最大值是多少

思路:
按照之前robber的思路,两种情况,抢和不抢,也是参考了大神的方法,定义一个长度为2的数组,[0]表示不抢,[1]表示抢。
到一个节点的时候,如果它自身rob,那么子节点就不能rob, 这种情况就是节点[1] = left[0] + right[0] + val
如果节点本身不rob, 那么就是max(left[0], left[1]) + max(right[0], right[1])

    public int rob(TreeNode root) {
        int[] robVal = helper(root);
        return Math.max(robVal[0], robVal[1]);
    }
    
    public int[] helper(TreeNode root) {
        if (root == null) {
            return new int[2];
        }
        
        int[] val = new int[2];
        
        int[] left = helper(root.left);
        int[] right = helper(root.right);
        
        val[1] = left[0] + right[0] + root.val;
        val[0] = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);
        return val;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值