LeetCode (16) - Construct Binary Tree from Preorder and Inorder Traversal(파이썬, python)
❓ 문제
-
Given two integer arrays
preorder
andinorder
wherepreorder
is the preorder traversal of a binary tree andinorder
is the inorder traversal of the same tree, construct and return the binary tree.Example 1:
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
andinorder
consist of unique values.- Each value of
inorder
also appears inpreorder
. 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는 디버깅용으로 만든 부분이다.
정리를 잘 해주셔서 참고를 하면서 풀었다!