337. robbery III (tree dp)

After completion of the last lap after robbing a street and house, he discovered a thief can steal new areas. The region has only one entrance, which we call the "root." In addition to the "root", and only the houses a "parent" house associated therewith. After some reconnaissance, clever thief realized that "this place all the houses are arranged similar to a binary tree." If both houses are directly connected robbed the same night, the house alarm.

Calculated without touching the alarm, a thief can steal the maximum amount of night.

Example 1:

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

     3
    / \
   2 3
    \ \
     3 1

Output: 7
explains: a thief to steal the night can be the maximum amount = 3 + 3 + 1 = 7.


/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int rob(TreeNode root) {
        if(root==null)
            return 0;
        int[] res=helper(root);
        return Math.max(res[0],res[1]);
    }
    public int[] helper(TreeNode node)
    {

// considered from the bottom up, get each child node of the results, then consider the results of this node node of what is

// tree dp, for each node, we consider two cases, one is to take this node, then the left and right child nodes of the value of this node is certainly not wanted,

// One is not to take this node, the node for the child about to be taken is the maximum number, so every time dp arrays are two values,


        // declare a res array stores two values, 0 is the maximum value of this node contains node, a node that does not contain the maximum value of
        // for res [0], comprises a node, i.e. does not comprise left take left, right take does not include the right node, the RES [0] = left [. 1] right + [. 1];
        // to res [1], does not include node, the left, right to take that value does not matter, so the maximum value, RES [. 1] = Math.max (left [0], left [. 1]) + Math.max (right [0] + right [. 1]);
        int RES [] = new new int [2];
        
        IF (Node == null)
            return RES;
        int [] = left Helper (node.left);
        int [] = right Helper (node.right);
        RES [0] = left [. 1] right + [. 1] + node.val;
        RES [ . 1] = Math.max (left [0], left [. 1]) + Math.max (right [0], right [. 1]);
        return RES;
    }
}

Guess you like

Origin www.cnblogs.com/cold-windy/p/11461246.html