Maximum Score After Applying Operations on a Tree — LeetCode 2925 Python Solution
- Problem
- #2925
- Pattern
- Tree Traversal
- Reading time
- 4 min
- Source
- leetcode.com
The problem
There is an undirected tree with n nodes labeled from 0 to n - 1, and rooted at node 0. You are given a 2D integer array edges of length n - 1, where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree.
Example
- Input
- edges = [[0,1],[0,2],[0,3],[2,4],[4,5]], values = [5,2,5,2,1,1]
- Output
- 11
- Explanation
- We can choose nodes 1, 2, 3, 4, and 5. The value of the root is non-zero. Hence, the sum of values on the path from the root to any leaf is different than zero. Therefore, the tree is healthy and the score is values[1] + values[2] + values[3] + values[4] + values[5] = 11.
Python solution
class Solution:
def maximumScoreAfterOperations(
self, edges: List[List[int]], values: List[int]
) -> int:
def dfs(i: int, fa: int = -1) -> (int, int):
a = b = 0
leaf = True
for j in g[i]:
if j != fa:
leaf = False
aa, bb = dfs(j, i)
a += aa
b += bb
if leaf:
return values[i], 0
return values[i] + a, max(values[i] + b, a)
g = [[] for _ in range(len(values))]
for a, b in edges:
g[a].append(b)
g[b].append(a)
return dfs(0)[1]Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Tree Traversal
Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 2925. Maximum Score After Applying Operations on a Tree is filed here because LeetCode tags it Tree, which is the vocabulary this hub collects.
The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2925. Maximum Score After Applying Operations on a Tree?
- LeetCode 2925. Maximum Score After Applying Operations on a Tree is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2925. Maximum Score After Applying Operations on a Tree?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 2925. Maximum Score After Applying Operations on a Tree?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 2925. Maximum Score After Applying Operations on a Tree cover?
- LeetCode 2925. Maximum Score After Applying Operations on a Tree is tagged Tree, Depth-First Search and Dynamic Programming on LeetCode.