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.
Number of Ways to Assign Edge Weights I — Solution
The key insight is that for any path with k edges, exactly half of all 2^k weight combinations produce odd sums. This happens when an odd number of edges have weight 1. Best approach uses the mathematical formula 2^(k-1) where k is the depth of the deepest node. Time: O(n), Space: O(n)
Common Approaches
Approach
Time
Space
Notes
✓
Brute Force - Try All Weight Combinations
O(n + 2^k)
O(n + 2^k)
Generate all possible weight assignments and count those with odd sums
Mathematical Formula - Power of 2
O(n)
O(n)
Use mathematical insight that exactly half of all combinations give odd sums
Brute Force - Try All Weight Combinations — Algorithm Steps
Step 1: Use DFS to find all nodes at maximum depth
Step 2: Find path from root to any deepest node
Step 3: Generate all 2^k weight combinations for k edges
Step 4: Count combinations with odd total weight
Visualization
Tap to expand
Step-by-Step Walkthrough
1
Find Deepest Node
Use DFS to find maximum depth node
2
Extract Path
Get path from root to deepest node
3
Generate Combinations
Try all 2^k weight assignments
4
Count Odd Sums
Count combinations with odd total weight
Code -
solution.c — C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MOD 1000000007
#define MAXN 1005
int graph[MAXN][MAXN];
int degree[MAXN];
int maxDepth = 0;
int deepestNode = 1;
int path[MAXN];
int pathLen = 0;
void dfsDepth(int node, int parent, int depth, int n) {
if (depth > maxDepth) {
maxDepth = depth;
deepestNode = node;
}
for (int i = 0; i < degree[node]; i++) {
int neighbor = graph[node][i];
if (neighbor != parent) {
dfsDepth(neighbor, node, depth + 1, n);
}
}
}
int findPath(int node, int parent, int target, int currentPath[], int currentLen) {
currentPath[currentLen] = node;
currentLen++;
if (node == target) {
for (int i = 0; i < currentLen; i++) {
path[i] = currentPath[i];
}
pathLen = currentLen;
return 1;
}
for (int i = 0; i < degree[node]; i++) {
int neighbor = graph[node][i];
if (neighbor != parent) {
if (findPath(neighbor, node, target, currentPath, currentLen)) {
return 1;
}
}
}
return 0;
}
int solution(int n, int edges[][2], int edgeCount) {
// Initialize
memset(degree, 0, sizeof(degree));
// Build adjacency list
for (int i = 0; i < edgeCount; i++) {
int u = edges[i][0];
int v = edges[i][1];
graph[u][degree[u]++] = v;
graph[v][degree[v]++] = u;
}
// Find maximum depth and any node at that depth
maxDepth = 0;
deepestNode = 1;
dfsDepth(1, -1, 0, n);
// Find path from root to deepest node
int currentPath[MAXN];
findPath(1, -1, deepestNode, currentPath, 0);
// Number of edges in path
int numEdges = pathLen - 1;
// Count ways to assign weights (1 or 2) such that sum is odd
int oddCount = 0;
int totalCombinations = 1 << numEdges;
for (int mask = 0; mask < totalCombinations; mask++) {
int totalWeight = 0;
for (int i = 0; i < numEdges; i++) {
if (mask & (1 << i)) {
totalWeight += 1; // weight 1
} else {
totalWeight += 2; // weight 2
}
}
if (totalWeight % 2 == 1) {
oddCount++;
}
}
return oddCount % MOD;
}
int main() {
int n;
scanf("%d", &n);
int edges[MAXN][2];
// Simple parsing - read pairs
char line[10000];
fgets(line, sizeof(line), stdin); // consume newline
fgets(line, sizeof(line), stdin);
int edgeCount = 0;
char *token = strtok(line, "[],");
while (token != NULL && edgeCount < n - 1) {
edges[edgeCount][0] = atoi(token);
token = strtok(NULL, "[],");
if (token) {
edges[edgeCount][1] = atoi(token);
edgeCount++;
}
token = strtok(NULL, "[],");
}
printf("%d\n", solution(n, edges, edgeCount));
return 0;
}
Time & Space Complexity
Time Complexity
⏱️
O(n + 2^k)
O(n) for DFS to find deepest node, O(2^k) to generate all combinations where k is path length
n
2n
✓ Linear Growth
Space Complexity
O(n + 2^k)
O(n) for adjacency list and DFS stack, O(2^k) for storing all weight combinations
n
2n
⚡ Linearithmic Space
29.4K Views
MediumFrequency
~25 minAvg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡Explanation
AI Ready
💡 SuggestionTabto acceptEscto dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen
Algorithm Visualization
Pinch to zoom • Tap outside to close
Test Cases
0 passed
0 failed
3 pending
Select Compiler
Choose a programming language
Compiler list would appear here...
AI Editor Features
Header Buttons
💡
Explain
Get a detailed explanation of your code. Select specific code or analyze the entire file. Understand algorithms, logic flow, and complexity.
🔧
Fix
Automatically detect and fix issues in your code. Finds bugs, syntax errors, and common mistakes. Shows you what was fixed.
💡
Suggest
Get improvement suggestions for your code. Best practices, performance tips, and code quality recommendations.
💬
Ask AI
Open an AI chat assistant to ask any coding questions. Have a conversation about your code, get help with debugging, or learn new concepts.
Smart Actions (Slash Commands)
🔧
/fix Enter
Find and fix issues in your code. Detects common problems and applies automatic fixes.
💡
/explain Enter
Get a detailed explanation of what your code does, including time/space complexity analysis.
🧪
/tests Enter
Automatically generate unit tests for your code. Creates comprehensive test cases.
📝
/docs Enter
Generate documentation for your code. Creates docstrings, JSDoc comments, and type hints.
⚡
/optimize Enter
Get performance optimization suggestions. Improve speed and reduce memory usage.
AI Code Completion (Copilot-style)
👻
Ghost Text Suggestions
As you type, AI suggests code completions shown in gray text. Works with keywords like def, for, if, etc.
Tabto acceptEscto dismiss
💬
Comment-to-Code
Write a comment describing what you want, and AI generates the code. Try: # two sum, # binary search, # fibonacci
💡
Pro Tip: Select specific code before using Explain, Fix, or Smart Actions to analyze only that portion. Otherwise, the entire file will be analyzed.