Mmedv

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 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:

|E| = |V| - 1

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 (, , 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 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 tree

2. 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 0

3. 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) {}
};

List of problems

18

Comments5