1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
| class Solution { long max = 0; TreeNode r; Map<TreeNode, Long> map = new HashMap<>(); public int maxProduct(TreeNode root) { dfs(root); r = root;
dfs2(root); return (int)(max % 1000000007); }
public void dfs2(TreeNode root) { if (root == null) { return; }
if (root.left != null) { max =Math.max(max, map.get(root.left) * (map.get(r) - map.get(root.left))); dfs2(root.left); }
if (root.right != null) { max =Math.max(max, map.get(root.right) * (map.get(r) - map.get(root.right))); dfs2(root.right); } }
public void dfs(TreeNode root) { if (root == null) { return; } if (root.left != null) { dfs(root.left); } if (root.right != null) { dfs(root.right); }
map.put(root, map.getOrDefault(root, 0L) + root.val);
if (root.left != null) { map.put(root, map.getOrDefault(root.left, 0L) + map.get(root)); }
if (root.right != null) { map.put(root, map.getOrDefault(root.right, 0L) + map.get(root)); } } }
|