엔지니어 게시판
LeetCode 솔루션 분류

[7/14] 105. Construct Binary Tree from Preorder and Inorder Traversal

컨텐츠 정보

본문

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:

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.
Accepted
757,048
Submissions
1,289,214

관련자료

댓글 1

학부유학생님의 댓글

  • 익명
  • 작성일
Runtime: 335 ms, faster than 21.08% of Python3 online submissions for Construct Binary Tree from Preorder and Inorder Traversal.
Memory Usage: 88.7 MB, less than 25.00% of Python3 online submissions for Construct Binary Tree from Preorder and Inorder Traversal.
class Solution:
    def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
        if not preorder or not inorder: return None
        
        root = TreeNode(preorder[0])
        pivot = inorder.index(root.val)
        
        root.left = self.buildTree(preorder[1:pivot+1], inorder[:pivot])
        root.right = self.buildTree(preorder[pivot+1:], inorder[pivot+1:])
      
        return root
전체 404 / 1 페이지
번호
제목
이름

최근글


인기글


새댓글


Stats


알림 0