150 najlepszych wywiadówŚredni

Zrównoważone drzewo binarne

Szczegółowy przewodnik i implementacja Python dla problemu „Zrównoważonego drzewa binarnego”.

Oświadczenie o problemie

Średni

Biorąc pod uwagę drzewo binarne, określ, czy jest ono zrównoważone pod względem wysokości.

Drzewo binarne o zrównoważonej wysokości to drzewo binarne, w którym głębokość dwóch poddrzew każdego węzła nigdy nie różni się o więcej niż jeden.

Drzewo jest reprezentowane jako lista poziomów. Zaimplementuj funkcję isBalanced(root: list) -> bool.

Ograniczenia
  • The number of nodes in the tree is in the range [0, 5000]
  • -10000 <= Node.val <= 10000

Przykłady

Example 1
Input
[3,9,20,None,None,15,7]
Output
True
Explanation

The left subtree (rooted at 9) has depth 1, and the right subtree (rooted at 20) has depth 2. The difference is 1, so the tree is balanced.

Example 2
Input
[1,2,2,3,3,None,None,4,4]
Output
False
Explanation

The left subtree has depth 3 while the right subtree has depth 1. The difference is 2, so the tree is not balanced.

Example 3
Input
[]
Output
True
Explanation

An empty tree is considered balanced.

Need a Hint?
Rozważ użycie struktur danych specyficznych dla drzew, 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.