Drzewo AVL
Szczegółowy przewodnik i implementacja Python dla problemu „Drzewo AVL”.
1. Ucz się
Problem „Drzewa AVL” jest kluczowym wyzwaniem w sekcji Drzewa.
Ta implementacja koncentruje się na logice średniego poziomu w Python.
W dostarczanych przez nas rozwiązaniach priorytetem jest dokładność techniczna i czytelność kodu.
2. Real-World Applications
3. Visual Intuition
Wizualizacja przepływu logicznego dla drzewa AVL.
4. Prerequisites
5. Step-by-Step Thinking
1. Understand the problem
Przeczytaj uważnie opis problemu dla drzewa AVL.
2. Formulate brute force
Zaprojektuj proste rozwiązanie iteracyjne.
3. Identify inefficiency
Poszukaj zbędnych obliczeń.
4. Optimize search path
Użyj funkcji mieszania lub sortowania, aby przyspieszyć proces.
5. Final Implementation
Oczyść kod dla standardów produkcyjnych.
Oświadczenie o problemie
Napisz funkcję is_avl_balanced(tree_arr), która pobiera tablicową reprezentację drzewa binarnego tree_arr i zwraca True, jeśli drzewo ma zrównoważoną wysokość (dla każdego węzła wysokość jego lewego i prawego poddrzewa różni się co najwyżej o 1) i jest prawidłowym BST lub False w przeciwnym razie.
- •0 <= len(tree_arr) <= 1000
Przykłady
tree_arr = [3, 9, 20, None, None, 15, 7]
True
The tree is a valid BST and the depth difference of left/right subtrees of all nodes is at most 1.
tree_arr = [1, 2, None, 3, None, None, None, 4]
False
The tree is unbalanced because leaf node 4 is at depth 4 while right subtree of node 1 is empty.
Need a Hint?
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.
Spostrzeżenia i odmiany wywiadu
Podział analizy złożoności
Dlaczego Czas: Directly evaluates all possibilities.
Dlaczego kosmos: Uses standard local memory.
Dlaczego Czas: Optimized paths reduce total operations.
Dlaczego kosmos: May trade memory for speed.
Zoptymalizowany kod rozwiązania w języku Python
Zoptymalizowany kod rozwiązania w języku Python
def create_avl_tree_opt(arr: list) -> list:
class AVLTreeNode:
def __init__(self, val=0):
self.val = val
self.left = None
self.right = None
self.height = 1
def get_height(node):
return node.height if node else 0
def get_balance(node):
return get_height(node.left) - get_height(node.right) if node else 0
def rotate_right(y):
x = y.left
T2 = x.right
x.right = y
y.left = T2
y.height = 1 + max(get_height(y.left), get_height(y.right))
x.height = 1 + max(get_height(x.left), get_height(x.right))
return x
def rotate_left(x):
y = x.right
T2 = y.left
y.left = x
x.right = T2
x.height = 1 + max(get_height(x.left), get_height(x.right))
y.height = 1 + max(get_height(y.left), get_height(y.right))
return y
def insert(node, val):
if not node:
return AVLTreeNode(val)
if val < node.val:
node.left = insert(node.left, val)
else:
node.right = insert(node.right, val)
node.height = 1 + max(get_height(node.left), get_height(node.right))
balance = get_balance(node)
# Left Left
if balance > 1 and val < node.left.val:
return rotate_right(node)
# Right Right
if balance < -1 and val > node.right.val:
return rotate_left(node)
# Left Right
if balance > 1 and val > node.left.val:
node.left = rotate_left(node.left)
return rotate_right(node)
# Right Left
if balance < -1 and val < node.right.val:
node.right = rotate_right(node.right)
return rotate_left(node)
return node
if not arr: return []
root = None
for val in arr:
root = insert(root, val)
# Serialize level-order
res = []
queue = [root]
while queue:
curr = queue.pop(0)
if curr:
res.append(curr.val)
queue.append(curr.left)
queue.append(curr.right)
else:
res.append(None)
while res and res[-1] is None:
res.pop()
return resKod brutalnej siły (chroniony spoilerami)
Kod brutalnej siły (chroniony spoilerami)
def create_avl_tree_brute(arr: list) -> list:
# Standard AVL tree insertion with rotations, returns level order list
class AVLTreeNode:
def __init__(self, val=0):
self.val = val
self.left = None
self.right = None
self.height = 1
def get_height(node):
return node.height if node else 0
def get_balance(node):
return get_height(node.left) - get_height(node.right) if node else 0
def rotate_right(y):
x = y.left
T2 = x.right
x.right = y
y.left = T2
y.height = 1 + max(get_height(y.left), get_height(y.right))
x.height = 1 + max(get_height(x.left), get_height(x.right))
return x
def rotate_left(x):
y = x.right
T2 = y.left
y.left = x
x.right = T2
x.height = 1 + max(get_height(x.left), get_height(x.right))
y.height = 1 + max(get_height(y.left), get_height(y.right))
return y
def insert(node, val):
if not node:
return AVLTreeNode(val)
if val < node.val:
node.left = insert(node.left, val)
else:
node.right = insert(node.right, val)
node.height = 1 + max(get_height(node.left), get_height(node.right))
balance = get_balance(node)
if balance > 1 and val < node.left.val:
return rotate_right(node)
if balance < -1 and val > node.right.val:
return rotate_left(node)
if balance > 1 and val > node.left.val:
node.left = rotate_left(node.left)
return rotate_right(node)
if balance < -1 and val < node.right.val:
node.right = rotate_right(node.right)
return rotate_left(node)
return node
if not arr: return []
root = None
for val in arr:
root = insert(root, val)
return tree_to_list(root)Algorithm Pattern Checklist
When dealing with Trees data patterns.
- Are constraints clear?
- Is there a linear or logarithmic optimization possible?
Key Revision Notes
Obowiązują właściwości problemu Standard Trees.
Powiązane pytania
PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!
Polecane zasoby Pythona
Poszerzaj swoją wiedzę dzięki powiązanym interaktywnym samouczkom, ściągawkom i porównaniom kodów.
Pętle Pythona
Dowiedz się, jak używać pętli Pythona do iteracji danych. Opanuj pętle for, pętle while, przerywaj, kontynuuj i pętluj najlepsze praktyki dzięki interaktywnym przykładom.
Jak sortować listę w Pythonie
Dowiedz się, jak sortować listę w Pythonie za pomocą metody sort() i funkcji sorted(). Odkryj przykłady niestandardowego sortowania kluczy i odwrotnej kolejności.
Ściągawka dotycząca metod ciągów w Pythonie
Kompletny przewodnik dotyczący manipulacji ciągami znaków w języku Python. Opanuj formatowanie, wyszukiwanie, dzielenie, zastępowanie i sprawdzanie właściwości ciągów.
Python kontra JavaScript: który język programowania jest najlepszy?
Kompleksowe porównanie Pythona i JavaScript. Poznaj różnice w składni, wydajność, przypadki użycia (backend vs frontend) i przykłady kodowania.