Very simple Java solution


  • 0
    T

    Use status boolean to determine whether allowed to take or not. Runs in time but it does unnecessary computations. Maybe there's a way to memoize.

        public int rob(TreeNode root) {
            return rob(root, true);
        }
        
        int rob(TreeNode root, boolean status) {
            if(root == null)
                return 0;
            if(status) {
                return Math.max(root.val+rob(root.left, false)+rob(root.right, false), rob(root.left, true)+rob(root.right, true));
            }
            else {
                return rob(root.left, true)+rob(root.right, true);
            }
        }
    }```

Log in to reply
 

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