Albero AVL
Guida dettagliata e implementazione Python per il problema 'AVL Tree'.
1. Impara
Il problema dell'"Albero AVL" è una sfida chiave nella sezione Alberi.
Questa implementazione si concentra sulla logica di livello medio in Python.
Diamo priorità all'accuratezza tecnica e alla leggibilità del codice nelle soluzioni fornite.
2. Real-World Applications
3. Visual Intuition
Visualizzazione del flusso logico per AVL Tree.
4. Prerequisites
5. Step-by-Step Thinking
1. Understand the problem
Leggi attentamente la dichiarazione del problema per AVL Tree.
2. Formulate brute force
Elaborare una semplice soluzione iterativa.
3. Identify inefficiency
Cerca calcoli ridondanti.
4. Optimize search path
Utilizza l'hashing o l'ordinamento per accelerare il processo.
5. Final Implementation
Ripulire il codice per gli standard di produzione.
Dichiarazione del problema
Scrivi una funzione is_avl_balanced(tree_arr) che accetta una rappresentazione array di un albero binario tree_arr e restituisce True se l'albero è bilanciato in altezza (per ogni nodo, l'altezza dei suoi sottoalberi sinistro e destro differisce al massimo di 1) ed è un BST valido, o False altrimenti.
- •0 <= len(tree_arr) <= 1000
Esempi
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
- Strutture di input vuote
- Ingressi a elemento singolo
- Grandi limiti numerici
Pronto a risolvere?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.
Approfondimenti e variazioni dell'intervista
Scomposizione dell'analisi della complessità
Perché il tempo: Directly evaluates all possibilities.
Perché lo spazio: Uses standard local memory.
Perché il tempo: Optimized paths reduce total operations.
Perché lo spazio: May trade memory for speed.
Codice Python della soluzione ottimizzata
Codice Python della soluzione ottimizzata
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 resCodice forza bruta (protetto da spoiler)
Codice forza bruta (protetto da spoiler)
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
Si applicano le proprietà del problema degli alberi standard.
Domande correlate
PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!
Risorse Python consigliate
Espandi le tue conoscenze con tutorial interattivi, foglietti illustrativi e confronti di codici correlati.
Cicli Python
Scopri come utilizzare i loop Python per eseguire iterazioni sui dati. Padroneggia le best practice sui cicli for, while, interruzione, continua e loop con esempi interattivi.
Come ordinare un elenco in Python
Scopri come ordinare un elenco in Python utilizzando il metodo sort() e la funzione sorted(). Scopri l'ordinamento delle chiavi personalizzato e gli esempi di ordine inverso.
Foglio informativo sui metodi delle stringhe Python
Una guida di riferimento completa per la manipolazione delle stringhe Python. Padroneggia la formattazione, la ricerca, la divisione, la sostituzione e il controllo delle proprietà delle stringhe.
Python vs JavaScript: quale linguaggio di programmazione è il migliore?
Un confronto completo tra Python e JavaScript. Esplora le differenze di sintassi, le prestazioni, i casi d'uso (backend e frontend) ed esempi di codifica.