150 najlepszych wywiadówŚredni

Skonstruuj drzewo binarne

Szczegółowy przewodnik i implementacja Python dla problemu „Konstruuj drzewo binarne”.

Oświadczenie o problemie

Średni

Biorąc pod uwagę dwie tablice liczb całkowitych, preorder i inorder, gdzie preorder jest przejściem drzewa binarnego w porządku preorder, a inorder jest przejściem tego samego drzewa w kolejności inorder, skonstruuj i zwróć drzewo binarne.

Drzewo powinno zostać zwrócone jako lista kolejności poziomów. Zaimplementuj funkcję buildTree(preorder: list, inorder: list) -> list.

Ograniczenia
  • 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

Przykłady

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?
Rozważ użycie struktur danych specyficznych dla drzew, takich jak zestawy lub sterty.
Edge Cases to Watch
  • Puste struktury wejściowe
  • Wejścia jednoelementowe
  • Duże granice liczbowe

Gotowy do rozwiązania?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Otwórz w Edytorze
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

Polecane zasoby Pythona

Poszerzaj swoją wiedzę dzięki powiązanym interaktywnym samouczkom, ściągawkom i porównaniom kodów.