Advertisement
Guest User

Grokking #219 - 2

a guest
May 18th, 2022
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.74 KB | None | 0 0
  1.     Map<TreeNode, Integer> dp = new HashMap<>();
  2.    
  3.     int traverse(TreeNode root) {
  4.         int val = 0;
  5.        
  6.         if (root == null)
  7.             return 0;
  8.        
  9.         if (dp.containsKey(root)) {
  10.             return dp.get(root);
  11.         }
  12.        
  13.         if (root.left != null) {
  14.             val += traverse(root.left.left) + traverse(root.left.right);
  15.         }
  16.         if (root.right != null) {
  17.             val += traverse(root.right.left) + traverse(root.right.right);
  18.         }
  19.        
  20.         int cur = Math.max(val + root.val, traverse(root.left) + traverse(root.right));
  21.         dp.put(root, cur);
  22.        
  23.         return cur;
  24.     }
  25.    
  26.     public int rob(TreeNode root) {
  27.         return traverse(root);
  28.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement