DFS + Memorization


  • 0
    Y
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public int rob(TreeNode root) {
            Map<TreeNode, Integer> map = new HashMap<TreeNode, Integer>();
            map.put(null, 0);
            return helper(root, map);
        }
        
        private int helper(TreeNode root, Map<TreeNode, Integer> map) {
            if (root == null) return 0;
            int l = helper(root.left, map);
            int r = helper(root.right, map);
            int ret = l + r;
            int ll = 0, rr = 0;
            if (root.left != null) {
                ll = map.get(root.left.left) + map.get(root.left.right);
            }
            if (root.right != null) {
                rr = map.get(root.right.left) + map.get(root.right.right);
            }
            ret = Math.max(ret, ll + rr + root.val);
            map.put(root, ret);
            return ret;
        }
    }
    

Log in to reply
 

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