Red Huang

Red Huang

Is A Tree?

Solution
If a graph has a tree structure, it means that all points in this graph are interconnected and there are no cycles present. Therefore, determining the existence of cycles is the most important key to this problem. A simple method to check for cycles is to use the concept of sets, categorizing the currently known connections into the same set. We will design an example to explain this process step by step:

Input
1 2
2 3
4 6
2 5
2 4
5 6
0 0

First, we assume that all points are not in any set.
The first input: 1 2, indicates that 1 points to 2, so we categorize 1 and 2 into set I.

The second input: 2 3, indicates that 2 points to 3, so 3 also belongs to set I.

The third input: 4 6, indicates that 4 points to 6, so 4 and 6 belong to another set II.

The next input: 2 5, so 5 also belongs to set I.

The next input: 2 4, so all elements in this set that include 4 should be categorized into set I.

The last input: 5 6, indicates that 5 points to 6, but since 5 and 6 already belong to the same set, connecting two points within the same set will inevitably form a cycle, thus this graph is not a tree.

If after processing all inputs, all points belong to the same set, then this graph is a tree.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.