150 principais entrevistasMédio

Construir árvore binária

Guia detalhado e implementação de Python para o problema 'Construct Binary Tree'.

Declaração do problema

Médio

Dadas duas matrizes de números inteiros, pré-ordem e inordem, onde pré-ordem é a travessia de pré-ordem de uma árvore binária e inorder é a travessia de ordem inordial da mesma árvore, construa e retorne a árvore binária.

A árvore deve ser retornada como uma lista de ordem de nível. Implemente uma função buildTree(preorder: list, inorder: list) -> list.

Restrições
  • 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

Exemplos

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?
Considere usar estruturas de dados específicas de árvores, como conjuntos ou heaps.
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.

Abrir no Editor
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

Recursos Python recomendados

Expanda seu conhecimento com tutoriais interativos relacionados, folhas de dicas e comparações de código.