VOOZH about

URL: https://www.geeksforgeeks.org/dsa/disjoint-set-union-on-trees/

⇱ Disjoint Set Union on Trees - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Disjoint Set Union on Trees

Last Updated : 11 Jul, 2025

Given a tree and weights of nodes. Weights are non-negative integers. Task is to find maximum size of a subtree of a given tree such that all nodes are even in weights.

Prerequisite : Disjoint Set Union

Examples : 

Input : Number of nodes = 7
 Weights of nodes = 1 2 6 4 2 0 3
 Edges = (1, 2), (1, 3), (2, 4), 
 (2, 5), (4, 6), (6, 7)
Output : Maximum size of the subtree 
with even weighted nodes = 4 
Explanation : 
Subtree of nodes {2, 4, 5, 6} gives the maximum size.

Input : Number of nodes = 6
 Weights of nodes = 2 4 0 2 2 6
 Edges = (1, 2), (2, 3), (3, 4), 
 (4, 5), (1, 6)
Output : Maximum size of the subtree
with even weighted nodes = 6
Explanation : 
The given tree gives the maximum size.

Approach: 

We can find solution by simply running DFS on tree. DFS solution gives us answer in O(n). But, how can we use DSU for this problem? 
We first iterate through all edges. If both nodes are even in weights, we make union of them. Set of nodes with maximum size is the answer. If we use union-find with path compression then time complexity is O(n).

Below is the implementation of above approach :  


Output
Maximum size of the subtree with even weighted nodes = 4

Time complexity : O(q log n) where q is the number of edges and n is the number of nodes.

Space Complexity : O(n)

Comment
Article Tags: