Java solution, easy to understand.


  • 0
    T
    public class Solution {
        public int rob(TreeNode root) {
            return rob(root, false);
        }
    
        private int rob(TreeNode node, boolean isSelect){
            if (node == null) return 0;
    
            if (isSelect){
                return rob(node.left, false) + rob(node.right, false);
            }
            else {
                return Integer.max(node.val + rob(node.left, true) + rob(node.right, true),
                        rob(node.left, false) + rob(node.right, false));
            }
        }
    
        public static void main(String[] args) {
            TreeNode root = new TreeNode(3);
            root.left = new TreeNode(2);
            root.right = new TreeNode(3);
            root.left.right = new TreeNode(3);
            root.right.right = new TreeNode(1);
            System.out.println(new Solution().rob(root));
        }
    }
    

Log in to reply
 

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