1632. Deepest Path Weight
A hiking park has trails modelled by a binary tree root; each junction node carries a score val, possibly negative, and a trail runs from the root down to a leaf. The park wants its most demanding trail: among all root-to-leaf paths, keep only those that pass through the largest number of nodes, and among those return the largest sum of node values.
The answer is a number that can be negative, and the result type is long so large totals are safe. A leaf is a node with no children. The longest path always wins over a richer shorter one, even when its sum is lower. Aim for one traversal, O(n) time and O(h) extra space apart from the stack, with no deep recursion needed.
Example 1
- Input:
- root = [1,2,3,4,null,null,5]
- Output:
- 9
- Explanation:
The answer is 9. Both longest paths have three nodes: 1-3-5 sums to 9, beating 1-2-4 with 7.
Example 2
- Input:
- root = [1,-2,-3]
- Output:
- -1
- Explanation:
The answer is -1. Both paths have two nodes, and the larger sum is -1.
Constraints
1 ≤ nodes ≤ 1000; -104 ≤ Node.val ≤ 104
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms
Expected complexity
- Time
- O(n)
- Space
- O(h)