Construct Binary Tree from Preorder and Postorder Traversal — LeetCode 889 Python Solution
- Problem
- #889
- Pattern
- Tree Traversal
- Reading time
- 4 min
- Source
- leetcode.com
The problem
Given two integer arrays, preorder and postorder where preorder is the preorder traversal of a binary tree of distinct values and postorder is the postorder traversal of the same tree, reconstruct and return the binary tree. If there exist multiple answers, you can return any of them.
Example
- Input
- preorder = [1,2,4,5,3,6,7], postorder = [4,5,2,6,7,3,1]
- Output
- [1,2,3,4,5,6,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 constructFromPrePost(
self, preorder: List[int], postorder: List[int]
) -> Optional[TreeNode]:
def dfs(a: int, b: int, c: int, d: int) -> Optional[TreeNode]:
if a > b:
return None
root = TreeNode(preorder[a])
if a == b:
return root
i = pos[preorder[a + 1]]
m = i - c + 1
root.left = dfs(a + 1, a + m, c, i)
root.right = dfs(a + m + 1, b, i + 1, d - 1)
return root
pos = {x: i for i, x in enumerate(postorder)}
return dfs(0, len(preorder) - 1, 0, len(postorder) - 1)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 889. Construct Binary Tree from Preorder 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
Frequently asked questions
- How hard is LeetCode 889. Construct Binary Tree from Preorder and Postorder Traversal?
- LeetCode 889. Construct Binary Tree from Preorder and Postorder Traversal is rated Medium on LeetCode.
- What is the time complexity of LeetCode 889. Construct Binary Tree from Preorder and Postorder Traversal?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 889. Construct Binary Tree from Preorder and Postorder Traversal?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 889. Construct Binary Tree from Preorder and Postorder Traversal cover?
- LeetCode 889. Construct Binary Tree from Preorder and Postorder Traversal is tagged Tree, Array, Hash Table, Divide and Conquer and Binary Tree on LeetCode.