Trees
Trees are one of the key data structures in algorithms and appear in a wide range of problems.
A tree is a connected, acyclic, undirected graph.
A graph G = (V, E) is called a tree if it satisfies the following properties:
Connected — there is a path between every pair of vertices in the graph.
Acyclic — the graph contains no cycles.
In a tree with n vertices, there are always exactly n - 1 edges.
Fundamental Properties of a Tree
1. Connectivity and Uniqueness of Paths
In a tree, there is a unique path between any pair of vertices.
2. Number of Edges
For any tree:
3. No Cycles
Adding even a single edge to a tree always creates a cycle.
4. Root (for a rooted tree)
If one vertex is chosen as the root, the tree becomes directed from the root to its descendants. This is used in recursive traversals and algorithms (DFS, LCA, etc.).
5. Subtrees
Any vertex along with its descendants forms a subtree. A subtree is itself a tree.
6. Leaves
Vertices with zero children (in a rooted tree) are called leaves.
7. Depth and Height
Depth of a vertex is the distance from the root to that vertex.
Height of a tree is the maximum depth among all vertices.
8. Center of a Tree
The center is the vertex (or a pair of adjacent vertices) that minimizes the maximum distance to all other vertices.
Alternative Definitions of a Tree
The following definitions of a tree are equivalent and can be used in different contexts:
A cycle-free graph that becomes disconnected if any edge is removed.
A connected graph with n vertices and n - 1 edges.
An acyclic graph with n - 1 edges and exactly one connected component.
Representing Trees in Code
Depending on the problem and the type of tree (general, binary, rooted, etc.), different data structures are used:
1. Adjacency Lists
This approach is often used in competitive programming problems and when working with undirected or directed trees.
int n;
vector<vector<int>> tree(n); // tree with n vertices
// adding an edge between vertices u and v
tree[u].push_back(v);
tree[v].push_back(u); // for an undirected tree2. Parent Array
A very compact representation, especially useful when the tree is already constructed.
vector<int> parent(n); // parent[i] --- he parent of vertex i
// if i is the root, parent[i] is usually set to -1 or 03. Pointers / Structures (OOP Style)
Commonly used when constructing binary trees, tries, decorators, especially in Python/Java/C++ with object-oriented programming.
Binary Tree:
struct Node
{
int val;
Node* left;
Node* right;
Node(int v) : val(v), left(nullptr), right(nullptr) {}
};General Tree:
struct Node
{
int val;
vector<Node*> children;
Node(int v) : val(v) {}
};A connected undirected graph without loops or multiple edges is given. It is allowed to delete edges from the graph. The goal is to obtain a tree.
Input. The first line contains two integers – the number of vertices n~(1 \le n \le 100) and the number of edges m in the graph. The following m pairs of integers each represent an edge. It is guaranteed that the graph is connected.
Output. Print n - 1 pairs of integers — the edges that form a tree. The edges can be printed in any order.

4 4
1 2
2 3
3 4
4 11 2
2 3
3 4You are given a tree, which is a simple connected graph without cycles.
Find the maximum number of edges that can be removed from the tree to obtain a forest where each connected component contains an even number of nodes.
For example, in the tree with 4 nodes shown below, you can remove at most 1 edge to create an even forest.

Input. The first line contains two integers n~(2 \le n \le 100, n is even) and m — the number of nodes and edges. Each of the next m lines contains two integers representing the nodes connected by an edge in the tree. The root of the tree is node 1.
Output. Print the maximum number of edges that can be removed.

10 9
2 1
3 1
4 3
5 2
6 1
7 2
8 6
9 8
10 82Given the structure of a company, your task is to calculate for each employee the number of their subordinates.
Input. The first line has an integer n~(1 \le n \le 2 \cdot 10^5) — the number of employees. The employees are numbered 1, 2, ..., n, and employee 1 is the general director of the company.
After this, there are n − 1 integers: for each employee 2, 3, ... , n their direct boss in the company.
Output. Print n integers: for each employee 1, 2, ..., n the number of their subordinates.

5
1 1 2 34 1 1 0 0A tree consisting of n vertices is given.
The diameter of a tree is the maximum distance between two vertices. Find the diameter of the given tree.
Input. The first line contains an integer n~(1 \le n \le 2 \cdot 10^5) — the number of vertices in the tree. The vertices are numbered from 1 to n.
Each of the following n - 1 lines describes an edge and contains two integers a and b~(1 \le a, b \le n), indicating that there is an edge between vertices a and b.
Output. Print one integer — the diameter of the tree.

5
1 2
1 3
3 4
3 53A tree consisting of n vertices is given.
For each vertex, determine the maximum distance to any other vertex.
Input. The first line contains an integer n~(1 \le n \le 2 \cdot 10^5) — the number of vertices in the tree. The vertices are numbered from 1 to n.
The next n - 1 lines describe the edges: each line contains two integers a and b~(1 \le a, b \le n), indicating that there is an edge between vertices a and b.
Output. Print n integers. For each vertex from 1 to n, print the maximum distance to any other vertex in the tree.

5
1 2
1 3
3 4
3 52 3 2 3 3Roman's parents gave him an undirected, connected, weighted graph with n vertices and n - 1 edges. Roman wants to find the total length of all paths between every pair of vertices in the graph. The length of a path is defined as the sum of the weights of the edges it includes. Since the path from vertex u to vertex v is the same as the path from v to u, Roman treats them as a single path and does not distinguish between them.
Input. The first line contains an integer n~(2 \le n \le 10^5) — the number of vertices in the graph.
Each of the next n - 1 lines describes an edge and contains three integers: the numbers of the two vertices connected by the edge (vertices are numbered from 1 to n), and the weight of the edge.
Output. Print the total length of all distinct paths between all pairs of vertices, modulo 10^9.

3
1 2 1
1 3 386
1 2 5
1 3 1
2 4 2
2 5 4
2 6 390A rooted tree consisting of n vertices is given. Each vertex is painted in one of n colors. For each vertex v, determine the number of distinct colors that appear in the subtree rooted at v.
Input. The first line contains a single integer n~(1 \le n \le 10^6). The following n lines describe the vertices of the tree. The i-th line contains two integers p_i and c_i, where p_i is the parent of vertex i, and c_i is the color of vertex i~(1 \le c_i \le n). For the root of the tree, p_i = 0.
Output. Print n integers — one for each vertex from 1 to n. For each vertex, print the number of distinct colors in the subtree rooted at that vertex.

5
2 1
3 2
0 3
3 3
2 11 2 3 1 1After a long and busy work week, the residents of Manchester and Liverpool decided to go hiking for the weekend. While walking through the forest, they came across a unique tree consisting of n vertices. The vertices of the tree are numbered from 1 to n, and each one is painted in one of c possible colors.
To fight off boredom, they decided to test their logical thinking. The root of the tree is vertex 1. For each vertex, the participants decided to find its nearest ancestor that shares the same color.
Input. The first line contains two integers n and c~(1 \le n, c \le 10^5) — the number of vertices in the tree and the number of possible colors.
The second line contains n - 1 integers: the i-th of them indicates the parent of vertex i + 1.
The third line contains n integers — the colors of the vertices. Each color is an integer from 1 to c, inclusive.
Output. Print n integers in a single line: for each vertex, print the number of its nearest ancestor with the same color. If no such ancestor exists, print -1.
5 4
1 1 3 3
1 4 2 1 2-1 -1 -1 1 3In his spare time, Farmer John created his own video-sharing platform called MooTube. On MooTube, his cows can record, publish, and discover lots of funny videos. So far, the cows have uploaded n videos, numbered from 1 to n.
However, Farmer John doesn't fully understand how to help his cows find new videos they might enjoy. He wants to implement a recommendation system for each video — a list of "recommended videos" based on their similarity to videos already watched.
To determine how similar two videos are, John introduces a relevance metric. He manually evaluates n - 1 pairs of videos and assigns each pair a relevance score. Using these pairs, John builds a network where each video is a node in a graph, and the selected pairs are connected by edges with the given relevance values.
For convenience, John selects the n - 1 pairs in such a way that there is exactly one path between any two videos — in other words, the video network forms a tree.
He decides that the relevance between two videos should be defined as the minimum relevance among all edges along the path connecting them.
Now, Farmer John wants to choose a value k such that, for any video on MooTube, all other videos with relevance at least k to it will be displayed as recommendations. However, he worries that too many recommendations might distract his cows from producing milk, so he wants to precisely estimate how many videos would be recommended for various values of k.
Farmer John turns to you for help: you are given several queries, each consisting of a value k and a video number. For each query, you need to determine how many other videos would be recommended if the minimum required relevance is k.
Input. The first line contains two integers n and q~(1 \le n, q \le 5000) — the number of videos and the number of queries, respectively.
The next n − 1 lines describe pairs of videos whose relevance has been manually evaluated by Farmer John. Each of these lines contains three integers p_i, q_i и r_i~(1 \le p_i, q_i \le n, 1 \le r_i \le 10^9), , meaning that videos p_i and q_i are connected by an edge with relevance r_i.
Then follow q lines, each describing one of Farmer John’s queries. The i-th line contains two integers k_i and v_i~(1 \le k_i \le 10^9, 1 \le v_i \le n) — meaning that in the i-th query, Farmer John wants to know how many videos will be recommended for video v_i if the minimum acceptable relevance for recommendations is k = k_i.
Output. Print q lines. In the i-th line, output the answer to Farmer John's i-th query.

Example. Farmer John has established the following connections between videos:
Video 1 and video 2 have a relevance of 3,
Video 2 and video 3 have a relevance of 2,
Video 2 and video 4 have a relevance of 4.
Based on this data, we can compute the relevance between other pairs of videos:
Video 1 and video 3: relevance = min(3, 2) = 2,
Video 1 and video 4: relevance = min(3, 4) = 3,
Video 3 and video 4: relevance = min(2, 4) = 2.
Now let’s see which videos will be recommended for the following queries:
From video 2 with k = 1, videos 1, 3, and 4 will be recommended.
From video 1 with k = 3, videos 2 and 4 will be recommended.
From video 1 with k = 4, no videos will be recommended.
4 3
1 2 3
2 3 2
2 4 4
1 2
4 1
3 13
0
2The tree with n vertices is given. The edges of the tree have weights of only 0 or 1. Let’s find the XOR sum between all pairs of vertices. Compute the sum of all XOR sums.
Input. The first line contains the number of vertices n~(2 \le n \le 10^5) in the graph. The next n - 1 lines describe the edges. Each line contains three integers: the numbers of the vertices connected by the edge (vertices are numbered from 1 to n) and the weight of the edge (0 or 1).
Output. Print the sum of XOR sums between all pairs of vertices.

5
1 2 1
2 3 1
2 4 0
4 5 16A tree with n vertices numbered from 1 to n is given. The i-th edge of the tree connects vertices a_i and b_i. Vertex i is colored with color c_i (in this problem, colors are represented by integers).
A vertex x is considered good if the shortest path from vertex 1 to vertex x does not contain any other vertex with the same color as vertex x, except for x itself.
Find all good vertices.
Input. The first line contains an integer n~(2 \le n \le 10^5) — the number of vertices.
The second line contains n integers — the colors of the vertices: c_1, c_2, \dots, c_n~(1 \le c_i \le 10^5).
Each of the following n - 1 lines contains two integers a_i and b_i~(1 \le a_i, b_i \le n) — the edges of the tree.
Output. Print all good vertices, one per line, in ascending order of their indices.

6
2 7 1 8 2 8
1 2
3 6
3 2
4 3
2 51
2
3
4
610
3 1 4 1 5 9 2 6 5 3
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
9 101
2
3
5
6
7
8You are given a tree with n vertices and n − 1 edges. The vertices are numbered from 1 to n, and the i-th edge connects vertices a_i and b_i.
You have k colors available. For each vertex in the tree, you choose one of the k colors to paint it, subject to the following condition:
If the distance between two different vertices x and y is less than or equal to two, then x and y have different colors.
How many ways are there to color the tree? Find the answer modulo 10^9 + 7.
Input. The first line contains two numbers n and k~(1 \le n, k \le 10^5). Each of the following n - 1 lines contains two integers a_i and b_i~(1 \le a_i, b_i \le n).
Output. Print the number of ways to color the tree modulo 10^9 + 7
4 3
1 2
2 3
3 465 4
1 2
1 3
1 4
4 548There are n cities in the country and n - 1 bidirectional roads, such that it is possible to travel from any city to any other city using only these roads. The cities are numbered with integers from 1 to n inclusive.
Initially, all roads are considered to be in bad condition, but the government plans to improve the state of some of them. The citizens will be satisfied with the improvements if there is no more than one bad road on the path from the capital, located in city 1, to any other city.
Determine the number of ways to improve the quality of some roads to meet this requirement. Since the answer can be very large, output it modulo 10^9 + 7.
Input. The first line contains a single integer n~(2 \le n \le 2 \cdot 10^5) — the number of cities in the country. The second line contains n - 1 positive integers p_2, p_3, p_4, \cdots, p_n~(1 \le p_i \le i - 1), describing the roads in the country. The number p_i indicates that there is a road connecting city p_i and city i.
Output. Print the number of ways to improve the quality of the roads modulo 10^9 + 7.

3
1 146
1 2 2 1 515On clear summer days, Nyusha enjoys catching butterflies in the fresh air. But today, she encountered a particularly cunning butterfly — it flew into a labyrinth and tried to hide from her inside.
The labyrinth consists of n rooms, numbered from 1 to n, some of which are connected by corridors. It is known that there is exactly one simple path between any two rooms, passing only through the corridors. In other words, the labyrinth forms a tree with n vertices and n - 1 edges.
The entrance to the labyrinth is located in room number 1. A leaf is defined as any room connected to exactly one other room and not being the root (i.e., not room 1). Each leaf contains an exit from the labyrinth. The butterfly starts its flight from room 1, heading toward one of the exits. It moves at a constant speed, never turns around, and travels through one corridor per minute, moving to a neighboring room. All corridors are of equal length.
To catch the butterfly, Nyusha decided to enlist the help of some friends. Initially, each of them can take position in any room that contains an exit. As soon as the butterfly begins its journey from the entrance toward some exit, the friends may immediately start moving from their rooms toward the entrance. They move at the same speed as the butterfly. If any of them encounters the butterfly — whether in a room or in the middle of a corridor — it is considered caught. However, if the butterfly reaches an exit without encountering any of the friends, it successfully escapes to freedom.
Help Nyusha determine the minimum number of friends needed to guarantee catching the butterfly, regardless of which exit it chooses.
Input. The first line contains a single integer n~(2 \le n \le 200000) — the number of rooms in the labyrinth.
The following n - 1 lines describe the corridors connecting the rooms. Each line contains two integers u and v~(1 \le u, v \le n, u ≠ v) — the indices of the rooms connected by a corridor.
It is guaranteed that the given corridor system forms a tree.
Output. Print a single integer — the minimum number of friends required to guarantee that the butterfly will be caught.
3
1 2
1 324
1 2
2 3
2 41Kefa decided to celebrate his first big salary by going to a restaurant.
He lives near an unusual park. The park is a rooted tree with n vertices, rooted at vertex 1. Kefa's house is located at vertex 1 as well. Unfortunately for our hero, the park is inhabited by cats, and Kefa has already identified the vertices where the cats are located.
The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant, but he is very afraid of cats. Therefore, he will not go to a restaurant if, on the path from his house to the restaurant, he encounters more than m consecutive vertices with cats.
Your task is to help Kefa count the number of restaurants he can safely visit.
Input. The first line contains two integers n and m~(2 \le n \le 10^5, 1 \le m \le n) — the number of vertices in the tree and the maximum number of consecutive vertices with cats that Kefa can tolerate.
The second line contains n integers a_1, a_2, ..., a_n, where each a_i is either 0 (there is no cat at vertex i) or 1 (there is a cat at vertex i).
The following n - 1 lines contains the tree's edges in the format x_i~y_i~(1 \le x_i, y_i \le n, x_i \ne y_i), where x_i and y_i are vertices connected by an edge.
It is guaranteed that this set of edges forms a tree.
Output. Print the number of leaf vertices that Kefa can reach if there are no more than m consecutive vertices with cats on the way from his house.

7 1
1 1 0 0 0 0 1
1 2
1 3
2 4
2 5
3 6
3 728 2
1 1 0 1 0 1 0 1
1 2
2 3
2 5
2 6
3 4
6 7
6 82A tree with n vertices is given. Vertex 1 is considered the root. There is exactly one simple path between any two vertices.
Let d(i, j) denote the number of edges on the path from vertex i to vertex j.
Find the number of vertex pairs (i, j) such that the following equality holds:
Input. The first line contains a single integer n~(1 \le n \le 10^5) — the number of vertices in the tree.
Each of the next n - 1 lines contains two integers, describing the edges of the tree: the pairs of vertices connected by an edge.
Output. Print a single integer — the number of pairs (i, j) for which d(i, j) = d(i, 1) - d(j, 1) holds.
5
1 2
2 3
2 4
4 513You are given a binary tree, which is an acyclic connected undirected graph containing n vertices and n - 1 edges. Each vertex has a degree of no more than 3. The root is the vertex number 1, with its degree not exceeding 2.
Unfortunately, the root of the tree is infected. The following process is repeated n times:
Huseyn either selects a vertex that is not yet infected (and not yet removed) and removes it along with all its incident edges, or he takes no action.
After that, the infection spreads to every vertex connected by an edge to an already infected vertex (all previously infected vertices remain infected).
Help Huseyn determine the maximum number of vertices he can save from infection (note that removed vertices are not considered saved).
Input. The first line contains the number of vertices in the tree n~(2 \le n \le 3 \cdot 10^5).
Each of the following n - 1 lines contains two integers u_i and v_i~(1 \le u_i, v_i \le n), representing an edge of the tree.
It is guaranteed that the graph is a binary tree with the root at vertex 1.
Output. Print a single integer — the number of saved vertices.
4
1 2
2 3
2 427
1 2
1 5
2 3
2 4
5 6
5 72
Comments5