10ms Java solution


  • 0
    J
    public class Solution {
        private Map<TreeNode,Integer> totals = new HashMap<TreeNode,Integer>();
        
        public int rob(TreeNode root) {
            return robNode(root);
        }
        
        private int robChildren(TreeNode node) {
            int total = 0;
            
            if ( node != null ) {
                total = robNode(node.left) + robNode(node.right);
            }
            
            return total;
        }
    
        private int robNode(TreeNode node) {
            int total = 0;
            
            if ( node != null ) {
                if ( totals.containsKey(node) ) {
                    total = totals.get(node);
                } else {
                    int total1 = node.val + robChildren(node.left) + robChildren(node.right);
                    int total2 = robChildren(node);
                    
                    total = total1 > total2 ? total1 : total2;
                    totals.put(node, total);
                }
            }
    
            return total;
        }
    }

Log in to reply
 

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