Number of Ways to Assign Edge Weights I - Problem
You're given an undirected tree with n nodes labeled from 1 to n, rooted at node 1. The tree is represented by a 2D array edges where edges[i] = [u_i, v_i] indicates an edge between nodes u_i and v_i.
Your task: Assign each edge a weight of either 1 or 2. Find a node x at the maximum depth from the root, then count how many ways you can assign weights to the edges on the path from node 1 to node x such that the total path cost is odd.
Key points:
- Initially all edges have weight 0
- You must assign weight 1 or 2 to each edge
- Consider only edges in the path from root (1) to the deepest node
- Return the count modulo
10^9 + 7
Input & Output
example_1.py โ Basic Tree
$
Input:
n = 4, edges = [[1,2],[1,3],[2,4]]
โบ
Output:
2
๐ก Note:
Tree structure: 1-2-4 and 1-3. Deepest node is 4. Path 1โ2โ4 has 2 edges. We can assign weights (1,1), (1,2), (2,1), or (2,2). Sums are 2, 3, 3, 4. Exactly 2 assignments (1,2) and (2,1) give odd sum 3.
example_2.py โ Linear Tree
$
Input:
n = 3, edges = [[1,2],[2,3]]
โบ
Output:
2
๐ก Note:
Linear tree: 1-2-3. Deepest node is 3. Path 1โ2โ3 has 2 edges. Same analysis as example 1: 2^(2-1) = 2 ways give odd sums.
example_3.py โ Single Node
$
Input:
n = 1, edges = []
โบ
Output:
0
๐ก Note:
Only one node, no edges. Path length is 0, so no way to get an odd sum.
Constraints
- 1 โค n โค 105
- edges.length = n - 1
- The input represents a valid tree
- 1 โค ui, vi โค n
- ui โ vi
Visualization
Tap to expand
Understanding the Visualization
1
Build the Tree
Create graph from edges and root at node 1
2
Find Deepest Path
Use DFS to find the node at maximum depth
3
Count Edge Assignments
Apply formula: 2^(path_length - 1) for odd sums
Key Takeaway
๐ฏ Key Insight: For k edges in the path to the deepest node, exactly 2^(k-1) weight assignments produce odd total costs, giving us an O(n) mathematical solution.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code