int maxPath(TreeNode tree) { if (tree == null) { return 0; } if (map.containsKey(tree)) { return map.get(tree); } int res = tree.val; int left = maxPath(tree.left); int right = maxPath(tree.right); int maxPath = max(left, right); res = res + maxPath > 0 ? res + maxPath : 0; map.put(tree, res); return res; }