[LeetCode]337. House Robber III

来源:互联网 发布:nginx mp4点播 编辑:程序博客网 时间:2024/06/04 01:23

https://leetcode.com/problems/house-robber-iii/

树型House Robber,相邻的节点不能同时抢劫


dfs返回一个数组,res[0]是当前节点被抢劫的最大值,res[1]是当前节点未被抢劫的最大值

public class Solution {    public int rob(TreeNode root) {        int[] res = dfs(root);        return Math.max(res[0], res[1]);    }    private int[] dfs(TreeNode root) {        if (root == null) {            return new int[2];        }        int[] left = dfs(root.left);        int[] right = dfs(root.right);        int[] res = new int[2];        res[0] = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);        res[1] = root.val + left[0] + right[0];        return res;    }}


0 0
原创粉丝点击