LeetCode (16) - Construct Binary Tree from Preorder and Inorder Traversal(파이썬, python)

1 분 소요

❓ 문제

  • 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 tree, construct and return the binary tree.

    Example 1:

    img

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

    Example 2:

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

    Constraints:

    • 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.

Given Code

# 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]:
        

내 풀이

class Solution:
    def buildTree(self, preorder, inorder):
        def build(preorder, inorder):
            if len(preorder) == 0:
                return None
            now = preorder[0]
            node = TreeNode(val=now)
            index = inorder.index(now)

            left_len = index
            right_len = len(preorder) - left_len - 1

            left_i = inorder[:index]
            # print(now)
            # print('---', now, '---')
            left_p = preorder[1:left_len + 1]
            # print(left_p, left_i)
            node.left = build(left_p, left_i)

            right_i = inorder[index + 1:]
            right_p = preorder[left_len + 1:]
            # print(right_p, right_i)
            node.right = build(right_p, right_i)

            # print(node.val, node.left, node.right)
            return node

        return build(preorder, inorder)

중간중간 주석처리된 print는 디버깅용으로 만든 부분이다.

정리를 잘 해주셔서 참고를 하면서 풀었다!