150 najlepszych wywiadówŚredni

Wykres prawidłowego drzewa

Detailed guide and Python implementation for the 'Graph Valid Tree' problem.

Oświadczenie o problemie

Średni

Masz graf n węzłów oznaczonych od 0 do n - 1. Podana jest liczba całkowita n i lista krawędzi, gdzie krawędzie[i] = [ai, bi] wskazują, że pomiędzy węzłami ai i bi na wykresie istnieje nieskierowana krawędź.

Return True if the edges of the given graph make up a valid tree, and False otherwise.

Napisz funkcję validTree(n: int, edges: List[List[int]]) -> bool.

Ograniczenia
  • 1 <= n <= 2000
  • 0 <= len(edges) <= 5000
  • edges[i].length == 2
  • 0 <= ai, bi < n

Przykłady

Example 1
Input
n = 5, edges = [[0,1],[0,2],[0,3],[1,4]]
Output
True
Explanation

The graph is fully connected and contains no cycles, so it is a valid tree.

Example 2
Input
n = 5, edges = [[0,1],[1,2],[2,3],[1,3],[1,4]]
Output
False
Explanation

The graph contains a cycle 1-2-3-1, so it is not a valid tree.

Need a Hint?
Rozważ użycie struktur danych specyficznych dla wykresów, takich jak zestawy lub sterty.
Edge Cases to Watch
  • Puste struktury wejściowe
  • Wejścia jednoelementowe
  • Duże granice liczbowe

Gotowy do rozwiązania?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Otwórz w Edytorze
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

Polecane zasoby Pythona

Poszerzaj swoją wiedzę dzięki powiązanym interaktywnym samouczkom, ściągawkom i porównaniom kodów.