본문 바로가기
Problem Solving/리트코드

[리트코드 leetcode] 105. Construct Binary Tree from Preorder and Inorder Traversal

by ggyongi 2021. 4. 13.
반응형

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

 

Construct Binary Tree from Preorder and Inorder Traversal - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

# 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]) -> TreeNode:
        
        def dfs(lst):
            if not lst:
                return
            
            mid = preorder.pop(0)
            idx = lst.index(mid)
            
            node = TreeNode(mid)
            node.left = dfs(lst[:idx])
            node.right = dfs(lst[idx+1:])
            
            return node

        root = dfs(inorder)
        return root
 

비전공자 네카라 신입 취업 노하우

시행착오 끝에 얻어낸 취업 노하우가 모두 담긴 전자책!

kmong.com

댓글