Tổ tiên chung thấp nhất của BST
Hướng dẫn chi tiết và cách triển khai Python cho bài toán 'Tổ tiên chung thấp nhất của BST'.
1. Tìm hiểu
Vấn đề 'Tổ tiên chung thấp nhất của BST' là một thách thức chính trong phần Cây cối.
Việc triển khai này tập trung vào logic cấp độ dễ 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 Tổ tiên chung thấp nhất của BST.
4. Prerequisites
5. Step-by-Step Thinking
1. Understand the problem
Đọc kỹ báo cáo vấn đề về Tổ tiên chung thấp nhất của BST.
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 đề
Cho cây tìm kiếm nhị phân (BST), tìm nút tổ tiên chung (LCA) thấp nhất của hai nút đã cho trong BST.
Theo định nghĩa của LCA: "Tổ tiên chung thấp nhất được xác định giữa hai nút p và q là nút thấp nhất trong T có cả p và q là hậu duệ (trong đó chúng tôi cho phép một nút là hậu duệ của chính nó)."
BST được biểu diễn dưới dạng danh sách thứ tự cấp độ. Triển khai hàm lowestCommonAncestor(root: list, p: int, q: int) -> int trả về giá trị của nút LCA.
- •The number of nodes in the tree is in the range [2, 100000]
- •-1000000000 <= Node.val <= 1000000000
- •All Node.val are unique
- •p != q
- •p and q will exist in the BST
Ví dụ
[6,2,8,0,4,7,9,None,None,3,5], 2, 8
6
The LCA of nodes 2 and 8 is 6, which is the root.
[6,2,8,0,4,7,9,None,None,3,5], 2, 4
2
The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself.
[2,1], 2, 1
2
The LCA of nodes 2 and 1 is 2.
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 lowest_common_ancestor_opt(root, p, q):
if isinstance(root, list):
r = build_tree(root)
val_p = p[0] if isinstance(p, list) else p
val_q = q[0] if isinstance(q, list) else q
def find_node(node, val):
if not node: return None
if node.val == val: return node
return find_node(node.left, val) or find_node(node.right, val)
node_p = find_node(r, val_p) or TreeNode(val_p)
node_q = find_node(r, val_q) or TreeNode(val_q)
res = lowest_common_ancestor_opt_helper(r, node_p, node_q)
return res.val if res else None
return lowest_common_ancestor_opt_helper(root, p, q)
def lowest_common_ancestor_opt_helper(root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode:
curr = root
while curr:
if p.val > curr.val and q.val > curr.val:
curr = curr.right
elif p.val < curr.val and q.val < curr.val:
curr = curr.left
else:
return currMã Brute Force (Bảo vệ spoiler)
Mã Brute Force (Bảo vệ spoiler)
def lowest_common_ancestor_brute(root, p, q):
if isinstance(root, list):
r = build_tree(root)
val_p = p[0] if isinstance(p, list) else p
val_q = q[0] if isinstance(q, list) else q
def find_node(node, val):
if not node: return None
if node.val == val: return node
return find_node(node.left, val) or find_node(node.right, val)
node_p = find_node(r, val_p) or TreeNode(val_p)
node_q = find_node(r, val_q) or TreeNode(val_q)
res = lowest_common_ancestor_brute_helper(r, node_p, node_q)
return res.val if res else None
return lowest_common_ancestor_brute_helper(root, p, q)
def lowest_common_ancestor_brute_helper(root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode:
if not root or root == p or root == q:
return root
left = lowest_common_ancestor_brute_helper(root.left, p, q)
right = lowest_common_ancestor_brute_helper(root.right, p, q)
if left and right:
return root
return left or rightAlgorithm 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 tìm độ dài của danh sách trong Python
Tìm hiểu cách tìm độ dài của danh sách trong Python bằng hàm len(). Hiểu độ phức tạp về thời gian O(1) và số lần kiểm tra.
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.