Construct Binary Tree from Inorder and Postorder Traversal — LeetCode 106 Python Solution
- Problem
- #106
- Pattern
- Tree Traversal
- Reading time
- 3 min
- Source
- leetcode.com
The problem
Given two integer arrays inorder and postorder where inorder is the inorder traversal of a binary tree and postorder is the postorder traversal of the same tree, construct and return the binary tree.
Example
- Input
- inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
- 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, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
def dfs(i: int, j: int, n: int) -> Optional[TreeNode]:
if n <= 0:
return None
v = postorder[j + n - 1]
k = d[v]
l = dfs(i, j, k - i)
r = dfs(k + 1, j + k - i, n - k + i - 1)
return TreeNode(v, l, r)
d = {v: i for i, v in enumerate(inorder)}
return dfs(0, 0, len(inorder))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 106. Construct Binary Tree from Inorder and Postorder 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 a study list
This problem is on Top Interview 150.
Frequently asked questions
- How hard is LeetCode 106. Construct Binary Tree from Inorder and Postorder Traversal?
- LeetCode 106. Construct Binary Tree from Inorder and Postorder Traversal is rated Medium on LeetCode.
- What is the time complexity of LeetCode 106. Construct Binary Tree from Inorder and Postorder Traversal?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 106. Construct Binary Tree from Inorder and Postorder Traversal?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 106. Construct Binary Tree from Inorder and Postorder Traversal cover?
- LeetCode 106. Construct Binary Tree from Inorder and Postorder Traversal is tagged Tree, Array, Hash Table, Divide and Conquer and Binary Tree on LeetCode.