본문 바로가기

알고리즘 스터디

[Leetcode/파이썬] 106. Construct Binary Tree from Inorder and Postorder Traversal

반응형

Construct Binary Tree from Inorder and Postorder Traversal

Difficulty: Medium


Given two integer arrays inorder and postorder where inorder is the inorder traversal of a binary tree and postorder is the postorder traversal of the same tree, construct and return the binary tree.

 

Example 1:

Input: inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
Output: [3,9,20,null,null,15,7]

Example 2:

Input: inorder = [-1], postorder = [-1]
Output: [-1]

 

Constraints:

  • 1 <= inorder.length <= 3000
  • postorder.length == inorder.length
  • -3000 <= inorder[i], postorder[i] <= 3000
  • inorder and postorder consist of unique values.
  • Each value of postorder also appears in inorder.
  • inorder is guaranteed to be the inorder traversal of the tree.
  • postorder is guaranteed to be the postorder traversal of the 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, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
        root_val = postorder.pop()
        idx = inorder.index(root_val)
        inorder_left = inorder[:idx]
        inorder_right = inorder[idx+1:]

        root = TreeNode(root_val)

        def travel(node, postorder, inorder_left, inorder_right) :
            if postorder and inorder_right :
                right_val = postorder.pop()
                node.right = TreeNode(right_val)
                right_idx = inorder_right.index(right_val)
                travel(node.right, postorder, inorder_right[:right_idx], inorder_right[right_idx+1:])

            if postorder and inorder_left :
                left_val = postorder.pop()
                node.left = TreeNode(left_val)
                left_idx = inorder_left.index(left_val)
                travel(node.left, postorder, inorder_left[:left_idx], inorder_left[left_idx+1:])

        travel(root, postorder, inorder_left, inorder_right)
        
        return root
# 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, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
        index_map = {v:i for i, v in enumerate(inorder)}
        def helper(s, e) :
            if s > e :
                return

            el = postorder.pop()
            si = index_map[el]
            root = TreeNode(inorder[si])

            root.right = helper(si+1, e)
            root.left = helper(s, si-1)
            return root

        return helper(0, len(inorder)-1)

저번에 풀었던거 하고 비슷한 유형 같은데 못 풀겠...

우선 inorder와 postorder 관계에 대해서 생각해보자

inorder : left - root - right

postorder : left - right - root

관계에 있으니까 이진 트리를 구성한다고 했을때, 무슨 관계가 있길래 될까.

오른쪽을 먼저 진행하면서 postorder의 리스트에서 계속 제거 해나가는건가? 

일단 postorder[-1] 은 무조건 root고

얼리 스탑 반환은 아마 이 노드는 빈 노드다 (이 노드의 상위 노드는 리프노드다) 라는 의미인 것 같다. 

약간 스택에 쌓이는걸 이용해서 root - right - left 처리를 하고 싶은 구조일까?

진행 방향은 알겠는데 preorder - inorder - postorder 의 관계, 그리고 이걸 단순 스택으로 봤을 때 나타내는 의미 이런거를 같이 공부해봐야겠다. 

반응형