Cây AVL
Hướng dẫn chi tiết và cách triển khai Python cho bài toán 'Cây AVL'.
1. Tìm hiểu
Bài toán 'Cây AVL' là một thách thức chính trong phần Cây.
Việc triển khai này tập trung vào logic cấp trung bình trong Python.
Chúng tôi ưu tiên độ chính xác về mặt kỹ thuật và khả năng đọc mã trong các giải pháp được cung cấp của chúng tôi.
2. Real-World Applications
3. Visual Intuition
Trực quan hóa luồng logic cho Cây AVL.
4. Prerequisites
5. Step-by-Step Thinking
1. Understand the problem
Đọc kỹ báo cáo vấn đề của AVL Tree.
2. Formulate brute force
Soạn thảo một giải pháp lặp lại đơn giản.
3. Identify inefficiency
Tìm các phép tính dư thừa.
4. Optimize search path
Sử dụng hàm băm hoặc sắp xếp để tăng tốc quá trình.
5. Final Implementation
Làm sạch mã cho tiêu chuẩn sản xuất.
Tuyên bố vấn đề
Viết hàm is_avl_balanced(tree_arr) lấy biểu diễn mảng của cây nhị phân tree_arr và trả về True nếu cây cân bằng chiều cao (đối với mỗi nút, chiều cao của cây con bên trái và bên phải của nó khác nhau tối đa 1) và là BST hợp lệ hoặc False nếu không.
- •0 <= len(tree_arr) <= 1000
Ví dụ
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
- Cấu trúc đầu vào trống
- Đầu vào phần tử đơn
- Giới hạn số lớn
Sẵn sàng để giải quyết?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.
Thông tin chi tiết và biến thể của cuộc phỏng vấn
Phân tích độ phức tạp
Tại sao thời gian: Directly evaluates all possibilities.
Tại sao không gian: Uses standard local memory.
Tại sao thời gian: Optimized paths reduce total operations.
Tại sao không gian: May trade memory for speed.
Mã Python giải pháp tối ưu hóa
Mã Python giải pháp tối ưu hóa
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 resMã Brute Force (Bảo vệ spoiler)
Mã Brute Force (Bảo vệ 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
Áp dụng các thuộc tính bài toán của Cây Tiêu chuẩn.
Câu hỏi liên quan
PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!
Tài nguyên Python được đề xuất
Mở rộng kiến thức của bạn với các hướng dẫn tương tác, bảng ghi chú và so sánh mã có liên quan.
Vòng lặp Python
Tìm hiểu cách sử dụng vòng lặp Python để lặp lại dữ liệu. Nắm vững các phương pháp hay nhất về vòng lặp for, while, ngắt, tiếp tục và lặp bằng các ví dụ tương tác.
Cách sắp xếp danh sách trong Python
Tìm hiểu cách sắp xếp danh sách trong Python bằng phương thức Sort() và hàm Sort(). Khám phá các ví dụ về sắp xếp khóa tùy chỉnh và thứ tự đảo ngược.
Bảng cheat phương thức chuỗi Python
Hướng dẫn tham khảo đầy đủ về thao tác chuỗi Python. Làm chủ định dạng, tìm kiếm, phân tách, thay thế và kiểm tra thuộc tính chuỗi.
Python vs JavaScript: Ngôn ngữ lập trình nào tốt nhất?
So sánh toàn diện giữa Python và JavaScript. Khám phá sự khác biệt về cú pháp, hiệu suất, trường hợp sử dụng (phụ trợ so với giao diện người dùng) và các ví dụ về mã hóa.