500. Maximum Sum of Longest Root-to-Leaf Paths in a Binary Tree
Maximum Sum of Longest Root-to-Leaf Paths in a Binary Tree

You are given a binary tree with n nodes numbered from 0 to n - 1. Node 0 is the root. Each node has an integer value, which may be negative.

A root-to-leaf path starts at the root and moves down through child nodes until it reaches a leaf. A leaf is a node with no left child and no right child. A node with only one child is not a leaf. The length of a path is the number of nodes on it, and the sum of a path is the total of the values of those nodes.

Among all root-to-leaf paths with the longest length, return the maximum sum.

Method Signature

int maxSumOfLongestPath(List<String> nodes)
  • nodes.get(i) describes node i in the format "value,left,right".
  • value is the value of node i.
  • left is the left child of node i, or -1 if node i has no left child.
  • right is the right child of node i, or -1 if node i has no right child.
  • Returns the maximum sum among all longest root-to-leaf paths.

Constraints

  • 1 ≤ n == nodes.size() ≤ 10,000
  • Each nodes[i] contains exactly three integers separated by commas, with no spaces.
  • -100,000 ≤ value ≤ 100,000
  • left == -1 or 1 ≤ left ≤ n - 1
  • right == -1 or 1 ≤ right ≤ n - 1
  • Each node from 1 to n - 1 appears exactly once as a left or right child across all of nodes.
  • Every node can be reached from the root.

Examples

Example 1

maxSumOfLongestPath(nodes = ["3,1,2", "-1,3,4", "4,-1,5", "2,-1,-1", "6,-1,-1", "-5,6,-1", "1,-1,-1"])

Output: 3

Explanation:

  • Path 0 → 1 → 3 has length 3 and sum 3 + (-1) + 2 = 4.
  • Path 0 → 1 → 4 has length 3 and sum 3 + (-1) + 6 = 8.
  • Node 2 has only a right child, so it is not a leaf. Path 0 → 2 → 5 → 6 has length 4 and sum 3 + 4 + (-5) + 1 = 3.
  • The only longest path has length 4, so the answer is 3, even though a shorter path has a larger sum.

Example 2

maxSumOfLongestPath(nodes = ["5,1,2", "2,3,4", "-3,5,6", "1,-1,-1", "4,-1,-1", "10,-1,-1", "6,-1,-1"])

Output: 12

Explanation:

  • All four root-to-leaf paths have length 3: 0 → 1 → 3 = 8, 0 → 1 → 4 = 11, 0 → 2 → 5 = 12, 0 → 2 → 6 = 8.
  • All of them are longest paths, and the maximum sum among them is 12.

Example 3

maxSumOfLongestPath(nodes = ["-4,1,2", "-6,-1,-1", "-2,-1,-1"])

Output: -6

Explanation:

  • Path 0 → 1 has sum -10 and path 0 → 2 has sum -6. Both have length 2.
  • The maximum sum among the longest paths is -6.


Please use Laptop/Desktop or any other large screen to add/edit code.