반응형
leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
# 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
댓글