Thinking process

public class Solution {
    public int rob(TreeNode root) {
        int[] result = dfsHelper(root);
        return Math.max(result[0], result[1]);
    }

    //int[] = {rob, not rob}
    private int[] dfsHelper(TreeNode node) {
        //exit
        if (node == null) return new int[2];

        int[] left = dfsHelper(node.left);
        int[] right = dfsHelper(node.right);

        int[] result = new int[2];

        //rob
        result[0] = left[1] + right[1] + node.val;
        //not rob
        result[1] = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);

        return result;
    }
}

results matching ""

    No results matching ""