Scribbling

LeetCode: 105. Construct Binary Tree from Preorder and Inorder Traversal 본문

Computer Science/Coding Test

LeetCode: 105. Construct Binary Tree from Preorder and Inorder Traversal

focalpoint 2021. 10. 20. 16:42

재귀로 풀어주자

# 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]:
        return self.builder(preorder, inorder)
    
    def builder(self, preorder, inorder):
        if not preorder:
            return None
        
        head = TreeNode(val=preorder[0])
                
        boundary_idx = inorder.index(preorder[0])
        left_preorder = preorder[1:boundary_idx+1]
        left_inorder = inorder[:boundary_idx]
        right_preorder = preorder[boundary_idx+1:]
        right_inorder = inorder[boundary_idx+1:]
        
        head.left = self.builder(left_preorder, left_inorder)
        head.right = self.builder(right_preorder, right_inorder)
        
        return head