Published:
Updated:

  • index ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•ด๋„ ๋จ
  • collections.deque(preorder).popleft()๋ฅผ ์‚ฌ์šฉํ–ˆ์–ด์„œ ๊ณ„์† ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ๋˜ ๊ฑฐ์˜€์Œ
    • ์ด๋Š” ๋”ฐ๋กœ ๋‚ด์žฅ ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“ค์–ด์„œ deque๋ฅผ ๋Œ์•„์ฃผ๊ฒŒ๋” ํ•˜๋Š” ๋ฐฉ์‹์œผ๋กœ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ์Œ
    • ์ด ์‹์€ ๊ณ„์† ์ƒˆ๋กœ์šด deque๋ฅผ ๋งŒ๋“ ๋‹ค๋Š” ๊ฒƒ


Solution

# Definition for a binary tree node.
import collections
from typing import Optional, List


class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution:
    # ์ฃผ์–ด์ง„ inorder, preorder ๊ฐ’์œผ๋กœ ํŠธ๋ฆฌ ๋งŒ๋“œ๋Š” ๋ฌธ์ œ
    def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
        if not inorder:
            return None

        # preorder ALWAYS has the node first.
        # But you don't know the size of either branch.
        pre_popleft = preorder.pop(0)
        # pre_popleft = collections.deque(preorder).popleft()

        # inorder ALWAYS has the left branch to the left of the node
        # and right branch to the right of the node.
        # So now you know the size of each branch.
        index = 0
        for x in inorder:
            if x == pre_popleft:
                break

            index += 1

        node = TreeNode(inorder[index])

        node.left = self.buildTree(preorder, inorder[:index])
        node.right = self.buildTree(preorder, inorder[index + 1:])

        return node


Reference

Leave a comment