【Leetcode】:337. House Robber III 问题 in JAVA

解决一个二叉树问题,目标是在遵循特定规则的情况下找到节点值的最大总和:不能选取相邻的节点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

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.

题目要求在一个给定的二叉树中求出一个最大值,该最大值是节点的val的和,给了一个限制条件:所选取的node不能直接相连,也就是说在求和中计算了某个节点X,那么该节点的两个子节点就不能再求和了。


参考了别人的思路“https://leetcode.com/discuss/91597/easy-understanding-solution-with-dfs”


使用递归的结构来处理很简单,只需要区分出偷该节点和不偷该节点的情况即可

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int rob(TreeNode root) {
        int[] res = dfs(root);
        return res[0] > res[1] ? res[0] : res[1];
    }
    //返回数组0下标表示偷该节点的收益,数组下标1表示不偷该节点的受益
    private int[] dfs(TreeNode root) {
        if (root == null) {
            return new int[2];
        }
        int[] res = new int[2];
        int[] left = dfs(root.left);
        int[] right = dfs(root.right);
        //偷这个节点,那么两个子节点不能偷
        res[0] = root.val + left[1] + right[1];
        //不偷这个节点,那么两个子节点随意
        res[1] = (left[0] > left[1] ? left[0] : left[1]) + (right[0] > right[1] ? right[0] : right[1]);
        return res;
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值