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

来源:互联网 发布:网络教育法学类本科 编辑:程序博客网 时间:2024/06/05 20:50

题目:

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;    }}



0 0
原创粉丝点击