[337]house robber

leetcode

The same question as the ** company party **

/**
 * 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]);

    }
    
    //result[0], indicates not choose root, result[1] indicates choose root
    
    public int[] helper(TreeNode root){
        
        int[] res = new int[2];
        res[1] = root.val;
        if(root.left == null && root.right == null)return res;
        
        if(root.left != null){
            int[] leftRes = helper(root.left);
            res[0] += Math.max(leftRes[1],leftRes[0]);
            res[1] += leftRes[0];
        }
        
        if(root.right != null){
            int[] rightRes = helper(root.right);
            res[0] += Math.max(rightRes[0],rightRes[1]);
            res[1] += rightRes[0];
        }
        
        
        return res;
    }
    
    
}

你可能感兴趣的:([337]house robber)