상위 150개 인터뷰중간

이진 트리 구축

'이진 트리 구성' 문제에 대한 자세한 가이드 및 Python 구현입니다.

문제 설명

중간

두 개의 정수 배열 preorder와 inorder가 주어지면 preorder는 이진 트리의 선순 순회이고 inorder는 동일한 트리의 중위 순회이며, 이진 트리를 구성하고 반환합니다.

트리는 레벨 순서 목록으로 반환되어야 합니다. buildTree(preorder: list, inorder: list) -> list 함수를 구현하세요.

제약
  • 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

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?
세트나 힙과 같은 트리 관련 데이터 구조를 사용해 보세요.
Edge Cases to Watch
  • 빈 입력 구조
  • 단일 요소 입력
  • 큰 수치 범위

해결할 준비가 되셨나요?

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

편집기에서 열기
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

권장 Python 리소스

관련 대화형 튜토리얼, 치트 시트, 코드 비교를 통해 지식을 확장하세요.