Árbol AVL
Guía detallada e implementación Python para el problema del 'Árbol AVL'.
1. aprender
El problema del 'Árbol AVL' es un desafío clave en la sección Árboles.
Esta implementación se centra en la lógica de nivel medio en Python.
Priorizamos la precisión técnica y la legibilidad del código en las soluciones que brindamos.
2. Real-World Applications
3. Visual Intuition
Visualizando el flujo lógico para AVL Tree.
4. Prerequisites
5. Step-by-Step Thinking
1. Understand the problem
Lea atentamente el planteamiento del problema de AVL Tree.
2. Formulate brute force
Redacte una solución iterativa simple.
3. Identify inefficiency
Busque cálculos redundantes.
4. Optimize search path
Utilice hash o clasificación para acelerar el proceso.
5. Final Implementation
Limpiar el código para los estándares de producción.
Declaración del problema
Escriba una función is_avl_balanced(tree_arr) que tome una representación de matriz de un árbol binario tree_arr y devuelva True si el árbol tiene una altura equilibrada (para cada nodo, la altura de sus subárboles izquierdo y derecho difiere en 1 como máximo) y es un BST válido, o False en caso contrario.
- •0 <= len(tree_arr) <= 1000
Ejemplos
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
- Estructuras de entrada vacías
- Entradas de un solo elemento
- Grandes límites numéricos
¿Listo para resolver?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.
Ideas y variaciones de la entrevista
Desglose del análisis de complejidad
Por qué el tiempo: Directly evaluates all possibilities.
Por qué el espacio: Uses standard local memory.
Por qué el tiempo: Optimized paths reduce total operations.
Por qué el espacio: May trade memory for speed.
Código Python de solución optimizada
Código Python de solución optimizada
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 resCódigo de fuerza bruta (spoiler guardado)
Código de fuerza bruta (spoiler guardado)
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
Se aplican las propiedades del problema de árboles estándar.
Preguntas relacionadas
PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!
Recursos recomendados de Python
Amplíe sus conocimientos con tutoriales interactivos relacionados, hojas de trucos y comparaciones de códigos.
Bucles de Python
Aprenda a utilizar bucles de Python para iterar sobre datos. Domine los bucles for, while, rompa, continúe y realice bucles con ejemplos interactivos.
Cómo ordenar una lista en Python
Aprenda a ordenar una lista en Python usando el método sort() y la función sorted(). Descubra ejemplos de ordenación inversa y clasificación de claves personalizadas.
Hoja de trucos sobre métodos de cadenas de Python
Una guía de referencia completa para la manipulación de cadenas de Python. Domine el formateo, la búsqueda, la división, el reemplazo y la verificación de las propiedades de las cadenas.
Python vs JavaScript: ¿Qué lenguaje de programación es mejor?
Una comparación completa entre Python y JavaScript. Explore las diferencias de sintaxis, el rendimiento, los casos de uso (backend frente a frontend) y ejemplos de codificación.