Number of Ways to Assign Edge Weights I - Problem

There is an undirected tree with n nodes labeled from 1 to n, rooted at node 1. The tree is represented by a 2D integer array edges of length n - 1, where edges[i] = [ui, vi] indicates that there is an edge between nodes ui and vi.

Initially, all edges have a weight of 0. You must assign each edge a weight of either 1 or 2.

The cost of a path between any two nodes u and v is the total weight of all edges in the path connecting them.

Select any one node x at the maximum depth. Return the number of ways to assign edge weights in the path from node 1 to x such that its total cost is odd.

Since the answer may be large, return it modulo 109 + 7.

Note: Ignore all edges not in the path from node 1 to x.

Input & Output

Example 1 — Linear Path Tree
$ Input: n = 4, edges = [[1,2],[2,3],[3,4]]
Output: 4
💡 Note: Tree is 1→2→3→4. Maximum depth is 3. Path 1→4 has 3 edges. We need odd total weight. Possible assignments: [1,2,2]=5, [2,1,2]=5, [2,2,1]=5, [1,1,1]=3. Total: 4 ways.
Example 2 — Single Edge Tree
$ Input: n = 2, edges = [[1,2]]
Output: 1
💡 Note: Tree is 1→2. Maximum depth is 1. Path has 1 edge. For odd sum, assign weight 1. Only 1 way: [1]=1.
Example 3 — Branched Tree
$ Input: n = 5, edges = [[1,2],[1,3],[2,4],[2,5]]
Output: 2
💡 Note: Tree has nodes 4 and 5 at max depth 2. Path 1→2→4 has 2 edges. For odd sum: [1,2]=3 or [2,1]=3. Total: 2 ways.

Constraints

  • 1 ≤ n ≤ 105
  • edges.length == n - 1
  • 1 ≤ ui, vi ≤ n
  • The input represents a valid tree

Visualization

Tap to expand
Tree Edge Weight Assignment for Odd Path SumsInput Tree1234Deepest node: 4 (depth = 3)Weight Assignments (1 or 2)Path 1→2→3→4 has 3 edges[1,2,2] → sum=5 (odd) ✓[2,1,2] → sum=5 (odd) ✓[2,2,1] → sum=5 (odd) ✓[1,1,1] → sum=3 (odd) ✓[2,2,2] → sum=6 (even)[1,1,2] → sum=4 (even)[1,2,1] → sum=4 (even)[2,1,1] → sum=4 (even)Answer: 4 ways (out of 8 total)Formula: 2^(k-1) = 2^(3-1) = 4 where k = path lengthMathematical insight: Exactly half of all combinations give odd sums
Understanding the Visualization
1
Input Tree
Tree with n nodes, root at node 1
2
Find Deepest
Use DFS to find maximum depth node
3
Count Assignments
Calculate 2^(depth-1) weight combinations giving odd sums
Key Takeaway
🎯 Key Insight: For k edges, exactly 2^(k-1) weight assignments produce odd path sums
Asked in
Google 35 Amazon 28
29.4K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen