Simple Java Solution


  • 0
    L
    public class Solution {
        	public int rob(TreeNode root) {
    		int[] r =  robHelper(root);
    		return r[0];
    	}
    
    	int[] robHelper(TreeNode root) {
    		if (root == null) {
    			return new int[] { 0, 0 };
    		}
    		int[] leftRe = robHelper(root.left); 
    		int[] rightRe = robHelper(root.right); 
    		int notContain = leftRe[0] + rightRe[0];
    		int contain = Math.max(notContain, root.val + leftRe[1] + rightRe[1]);
    		return new int[]{contain,notContain};
    	}
    }
    

    The first result of the function robHelper save the best result.
    it is the max of (rob current hourse and not rob current hourse).


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.