Construct Binary Tree from Preorder and Inorder Traversal — LeetCode 105 Python Solution
- Problem
- #105
- Pattern
- Tree Traversal
- Reading time
- 3 min
- Source
- leetcode.com
The problem
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
- Input
- preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
- Output
- [3,9,20,null,null,15,7]
Python solution
# 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]:
def dfs(i: int, j: int, n: int) -> Optional[TreeNode]:
if n <= 0:
return None
v = preorder[i]
k = d[v]
l = dfs(i + 1, j, k - j)
r = dfs(i + 1 + k - j, k + 1, n - k + j - 1)
return TreeNode(v, l, r)
d = {v: i for i, v in enumerate(inorder)}
return dfs(0, 0, len(preorder))Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Tree Traversal
Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 105. Construct Binary Tree from Preorder and Inorder Traversal is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.
The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
On study lists
This problem is on Blind 75, NeetCode 150, Grind 75 and Top Interview 150.
Frequently asked questions
- How hard is LeetCode 105. Construct Binary Tree from Preorder and Inorder Traversal?
- LeetCode 105. Construct Binary Tree from Preorder and Inorder Traversal is rated Medium on LeetCode.
- What is the time complexity of LeetCode 105. Construct Binary Tree from Preorder and Inorder Traversal?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 105. Construct Binary Tree from Preorder and Inorder Traversal?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 105. Construct Binary Tree from Preorder and Inorder Traversal cover?
- LeetCode 105. Construct Binary Tree from Preorder and Inorder Traversal is tagged Tree, Array, Hash Table, Divide and Conquer and Binary Tree on LeetCode.