[LeetCode]Construct Binary Tree from Preorder and Inorder Traversal

2023. 6. 2. 19:15·SW개발/코딩테스트

https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/

 

Construct Binary Tree from Preorder and Inorder Traversal - LeetCode

Can you solve this real interview question? Construct Binary Tree from Preorder and Inorder Traversal - Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same

leetcode.com

 

문제 분석

전위 순회, 중위 순회 순서를 가지고 Binary Tree를 복구(생성)하는 문제입니다.

 

처음 시도한 답안

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
        # https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/solutions/748301/python3-solution-with-a-detailed-explanation-preorder-and-inorder-traversal/
        # https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/solutions/34579/Python-short-recursive-solution./comments/32947/

        # 기본적으로 전위 순회의 첫번째 값은 부모노드이고, 중위 순회 결과를 left, rigth로 나누는 역할을 한다.
        # 전위 순회의 값을 순차적으로 pop left 하면서 중위 순회를 left, right로 나눈다.

        # Fyi. 순회에는 크게 전위, 중위, 후위 순회가 있으며 이 셋 중 2가지만 있어도 이진 트리를 복원할 수 있다.

        # 순회할 요소가 남아있다면
        if inorder:
            val = preorder.pop(0)
            root = TreeNode(val)

            ind = inorder.index(val)

            # preorder에서 pop한 값을 기준으로 inorder 왼쪽은 왼쪽 자식 트리
            root.left = self.buildTree(preorder, inorder[0:ind])
            # preorder에서 pop한 값을 기준으로 inorder 오른쪽은 오른쪽 자식 트리
            root.right = self.buildTree(preorder, inorder[ind+1:])

            return root

접근 방법

  1. 전위 순회와 중위 순회를 알고 있으면 이진 트리를 복원할 수 있습니다.
  2. 전위 순회의 값은 중위 순회 결과를 Left 트리와 Right 트리로 나누게 됩니다.
  3. 따라서, 전위 순회 결과에서 pop left 하고 해당 값으로 루트 노드를 만듭니다.
  4. 중위 순회 결과에서 pop left한 값을 기준으로 루트의 왼쪽 자식, 루트의 오른쪽 자식 노드를 만들고 재귀적으로 호출합니다.
  5. 중위 순회를 더이상 순회할 수 없다면, 이진트리가 복원됭 상태입니다.

 

아래의 예시는 다음과 같이 순회하면서 트리를 생성합니다.

preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]

  1. preorder pop left(root) : 3, inorder_left = [9], inorder_right = [15,20,7]
    1. (inorder_left), pop left(root.left) : 9, inorder_left = [], inorder_right = []
    2. (inorder_right), pop left(root.right) : 20, inorder_left = [15], inorder_right = [7]
      1. (inorder_left), pop left(root.left) : 15, inorder_left = [], inorder_right = [] 
      2. (inorder_right), pop left(root.right) : 7, inorder_left = [], inorder_right = []

 

728x90

'SW개발 > 코딩테스트' 카테고리의 다른 글

[LeetCode]Kth Smallest Element in BST  (0) 2024.03.23
[Leetcode]Kth Largest Element in an Array  (0) 2024.03.22
[LeetCode]Binary Tree Level Order Traversal  (0) 2023.06.01
[LeetCode]Validate Binary Search Tree  (0) 2023.05.31
[LeetCode]Word Search  (0) 2023.05.30
'SW개발/코딩테스트' 카테고리의 다른 글
  • [LeetCode]Kth Smallest Element in BST
  • [Leetcode]Kth Largest Element in an Array
  • [LeetCode]Binary Tree Level Order Traversal
  • [LeetCode]Validate Binary Search Tree
Leffe_pt
Leffe_pt
개발자로서 성장하면서 배워온 지식과 경험을 공유하는 공간입니다.
  • Leffe_pt
    Leffe's tistory
    Leffe_pt
  • 전체
    오늘
    어제
    • 분류 전체보기 (307)
      • SW개발 (303)
        • 코딩테스트 (172)
        • 개발이야기 (23)
        • IT 용어 (17)
        • Python (22)
        • Django (46)
        • Flask (2)
        • Database (1)
        • SQLAlchemy (0)
        • Javascript (5)
        • Linux, Unix (3)
        • JAVA (2)
        • Spring (10)
      • 회고 (4)
      • 사진 (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    g
    배달비 공유
    django
    배공파용
    플레이스토어
    트리 #AVL #알고리즘 #자료구조
    음식
    배달
    오픈소스
    Contributor
    컨트리뷰터
    어플리케이션
    라이프 스타일
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Leffe_pt
[LeetCode]Construct Binary Tree from Preorder and Inorder Traversal
상단으로

티스토리툴바