Phỏng vấn top 150Trung bình

Xây dựng cây nhị phân

Hướng dẫn chi tiết và cách triển khai Python cho bài toán 'Xây dựng cây nhị phân'.

Tuyên bố vấn đề

Trung bình

Cho hai mảng số nguyên thứ tự trước và thứ tự trong đó thứ tự trước là lần duyệt thứ tự trước của cây nhị phân và thứ tự thứ tự là lần duyệt thứ tự của cùng một cây, xây dựng và trả về cây nhị phân.

Cây phải được trả về dưới dạng danh sách thứ tự cấp độ. Triển khai hàm buildTree(preorder: list, inorder: list) -> list.

Ràng buộc
  • 1 <= preorder.length <= 3000
  • inorder.length == preorder.length
  • -3000 <= preorder[i], inorder[i] <= 3000
  • preorder and inorder consist of unique values
  • Each value of inorder also appears in preorder
  • preorder is guaranteed to be the preorder traversal of the tree
  • inorder is guaranteed to be the inorder traversal of the tree

Ví dụ

Example 1
Input
[3,9,20,15,7], [9,3,15,20,7]
Output
[3,9,20,None,None,15,7]
Explanation

Preorder: root is 3. In inorder, 9 is to the left of 3 (left subtree) and [15,20,7] is to the right (right subtree). Recursively build: left subtree is just [9], right subtree has root 20 with children 15 and 7.

Example 2
Input
[-1], [-1]
Output
[-1]
Explanation

Single node tree.

Need a Hint?
Hãy cân nhắc sử dụng các cấu trúc dữ liệu dành riêng cho Cây như tập hợp hoặc đống.
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.

Mở trong Trình chỉnh sửa
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me 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.