House Robber III

来源:互联网 发布:中国域名交易中心 编辑:程序博客网 时间:2024/06/06 01:34
/** * 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) {        if (root == null) {            return 0;        }        int[] res = helper(root);        return Math.max(res[0], res[1]);    }        private int[] helper(TreeNode node) {        if (node == null) {            return new int[]{0, 0};        }        int[] left = helper(node.left);        int[] right = helper(node.right);        int[] res = new int[2];        res[0] = node.val + left[1] + right[1];        res[1] = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);        return res;    }}

0 0
原创粉丝点击