1641. Leaf to Leaf Best
A cave system is a binary tree and every node holds a treasure value, possibly negative. A leaf is a node with no children. Choose two different leaves and follow the unique path between them; its value is the sum of the values of every node on that path, both end leaves included.
Given root, return the maximum path value over all pairs of different leaves. If the tree has fewer than two leaves, return null (None in Python, an empty optional in C++).
Note that a node with exactly one child cannot be the turning point of a leaf-to-leaf path. Aim for O(n) time and O(n) space; the tree can be a long chain, so use an iterative traversal.
Example 1
- Input:
- root = [1,2,3]
- Output:
- 6
- Explanation:
The leaves are 2 and 3, and the path 2, 1, 3 sums to 6.
Example 2
- Input:
- root = [-10,5,null,3]
- Output:
- null
- Explanation:
The tree is a chain with a single leaf, so there is no pair of leaves and the answer is null.
Example 3
- Input:
- root = [9,-3,4,2,8,null,null,-1,1]
- Output:
- 18
- Explanation:
The best pair of leaves is 8 and 4 through the root: 8 - 3 + 9 + 4 = 18.
Constraints
1 ≤ nodes ≤ 105
-104 ≤ Node.val ≤ 104
generated trees shape random (iterative DFS advised)
pairing leaves is O(L^2)
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 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms
Expected complexity
- Time
- O(n)
- Space
- O(n)