Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save rungxanh1995/c1fa895b9993c070a01bf27a6454823f to your computer and use it in GitHub Desktop.
Save rungxanh1995/c1fa895b9993c070a01bf27a6454823f to your computer and use it in GitHub Desktop.

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.
# 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]:
# base case
if not preorder or not inorder:
return None
preorder_queue = collections.deque(preorder)
inorder_map = {value: key for key, value in enumerate(inorder)}
def buildTreeHelper(left_index: int, right_index: int):
# base case for indices
if left_index > right_index:
return None
root_value = preorder_queue.popleft() # keep track of value
curr_root = TreeNode(val=root_value)
midpoint = inorder_map[root_value] # O(1) by using dict
curr_root.left = buildTreeHelper(left_index, midpoint-1)
curr_root.right = buildTreeHelper(midpoint+1, right_index)
return curr_root
return buildTreeHelper(0, len(preorder) - 1) # only utilize the index of preorder, avoided time consumption creating lists for recursive calls
# 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]:
if not preorder or not inorder:
return None
curr_root = TreeNode(val=preorder[0]) # root is 1st element in preorder array
midpoint = inorder.index(preorder[0]) # 1st recursive value: 1
curr_root.left = self.buildTree(preorder=preorder[1:midpoint+1], inorder=inorder[:midpoint]) # construct left subtree
curr_root.right = self.buildTree(preorder=preorder[midpoint+1:], inorder=inorder[midpoint+1:]) # construct right subtree
return curr_root
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment