Árvore AVL
Guia detalhado e implementação de Python para o problema 'AVL Tree'.
1. Aprenda
O problema da 'Árvore AVL' é um desafio chave na seção Árvores.
Esta implementação concentra-se na lógica de nível médio em Python.
Priorizamos a precisão técnica e a legibilidade do código em nossas soluções fornecidas.
2. Real-World Applications
3. Visual Intuition
Visualizando o fluxo lógico para AVL Tree.
4. Prerequisites
5. Step-by-Step Thinking
1. Understand the problem
Leia a declaração do problema do AVL Tree com atenção.
2. Formulate brute force
Elabore uma solução iterativa simples.
3. Identify inefficiency
Procure cálculos redundantes.
4. Optimize search path
Use hashing ou classificação para acelerar o processo.
5. Final Implementation
Limpe o código para padrões de produção.
Declaração do problema
Escreva uma função is_avl_balanced(tree_arr) que pega uma representação de array de uma árvore binária tree_arr e retorna True se a árvore tiver balanceamento de altura (para cada nó, a altura de suas subárvores esquerda e direita difere em no máximo 1) e é um BST válido, ou False caso contrário.
- •0 <= len(tree_arr) <= 1000
Exemplos
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
- Estruturas de entrada vazias
- Entradas de elemento único
- Grandes limites numéricos
Pronto para resolver?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.
Insights e variações da entrevista
Análise de complexidade
Por que tempo: Directly evaluates all possibilities.
Por que espaço: Uses standard local memory.
Por que tempo: Optimized paths reduce total operations.
Por que espaço: May trade memory for speed.
Código Python da solução otimizada
Código Python da solução otimizada
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 força bruta (protegido por spoiler)
Código de força bruta (protegido por 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
Propriedades de problemas de árvores padrão se aplicam.
Perguntas relacionadas
PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!
Recursos Python recomendados
Expanda seu conhecimento com tutoriais interativos relacionados, folhas de dicas e comparações de código.
Loops Python
Aprenda como usar loops Python para iterar dados. Domine as práticas recomendadas para loops for, while loops, break, continue e loop com exemplos interativos.
Como classificar uma lista em Python
Aprenda como classificar uma lista em Python usando o método sort() e a função sorted(). Descubra exemplos de classificação de chaves personalizadas e ordem reversa.
Folha de dicas dos métodos de string Python
Um guia de referência completo para manipulação de strings em Python. Domine a formatação, pesquisa, divisão, substituição e verificação de propriedades de string.
Python vs JavaScript: qual linguagem de programação é a melhor?
Uma comparação abrangente entre Python e JavaScript. Explore diferenças de sintaxe, desempenho, casos de uso (backend versus frontend) e exemplos de codificação.