Tree traversal
pre-order traversal
post-order traversal
binary trees
algorithm techniques

Pre-order to post-order traversal

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

Converting pre-order traversal into post-order traversal depends on what information you have about the tree. For an arbitrary binary tree, pre-order alone is not enough to reconstruct a unique structure. For specific tree classes, such as binary search trees, conversion is possible and efficient.

Why Pre-Order Alone Is Usually Ambiguous

Pre-order records nodes in root, left, right order. Many different tree shapes can produce the same pre-order sequence, so post-order cannot be uniquely determined without extra constraints.

Example sequence: 10 5 1 7 40 50

This sequence can represent different binary trees unless you know rules such as BST ordering. Always state assumptions before implementing conversion logic.

Convert Pre-Order to Post-Order for BST

For a BST, pre-order uniquely determines structure when keys are distinct. We can reconstruct post-order in linear time by scanning pre-order with value bounds.

Idea:

  • first value in range is current root
  • values smaller than root belong to left subtree
  • values larger than root belong to right subtree
  • output root after processing both subtrees
python
1from typing import List
2
3
4def preorder_to_postorder_bst(preorder: List[int]) -> List[int]:
5    i = 0
6    n = len(preorder)
7    post = []
8
9    def build(lower: float, upper: float) -> None:
10        nonlocal i
11        if i >= n:
12            return
13
14        value = preorder[i]
15        if value <= lower or value >= upper:
16            return
17
18        i += 1
19        build(lower, value)   # left subtree
20        build(value, upper)   # right subtree
21        post.append(value)    # post-order step
22
23    build(float("-inf"), float("inf"))
24    return post
25
26
27if __name__ == "__main__":
28    pre = [10, 5, 1, 7, 40, 50]
29    print(preorder_to_postorder_bst(pre))  # [1, 7, 5, 50, 40, 10]

Time complexity is linear because each value is consumed once. Space complexity is proportional to recursion depth.

Validate Input for BST Assumptions

If input does not actually represent a BST pre-order sequence, conversion can return partial or misleading output. Add validation by ensuring all nodes are consumed.

python
1def preorder_to_postorder_bst_checked(preorder):
2    i = 0
3    post = []
4
5    def build(lower, upper):
6        nonlocal i
7        if i >= len(preorder):
8            return
9        v = preorder[i]
10        if not (lower < v < upper):
11            return
12        i += 1
13        build(lower, v)
14        build(v, upper)
15        post.append(v)
16
17    build(float("-inf"), float("inf"))
18    if i != len(preorder):
19        raise ValueError("Input is not a valid BST preorder sequence")
20    return post

This prevents silent failures in production pipelines.

If Tree Is Not a BST, You Need More Data

For a general binary tree, pre-order plus one extra traversal is typically required to reconstruct structure:

  • pre-order plus in-order for unique trees without duplicates
  • pre-order plus post-order for full binary trees under additional constraints

With reconstructed structure, post-order is straightforward.

python
1class Node:
2    def __init__(self, val):
3        self.val = val
4        self.left = None
5        self.right = None
6
7
8def postorder(root):
9    if root is None:
10        return []
11    return postorder(root.left) + postorder(root.right) + [root.val]

The critical step is that reconstruction must be uniquely defined. Without that, conversion remains ambiguous.

Iterative Traversal Note

If recursion depth is a concern on skewed trees, iterative traversal with explicit stacks can avoid recursion limits. For conversion from pre-order in BST form, recursive bound logic is usually simpler and fast enough for moderate sizes. For very deep trees, consider iterative parsing or increase recursion limits carefully with operational safeguards.

Common Pitfalls

  • Assuming pre-order uniquely identifies a general binary tree.
  • Forgetting to define duplicate-key policy for BST inputs.
  • Skipping validation and returning output even when input is invalid for assumed rules.
  • Using recursion on extremely deep skewed trees without considering stack depth.
  • Mixing zero-based indexes and bound logic incorrectly during parser implementation.

Summary

  • Pre-order to post-order conversion needs structural assumptions.
  • For BST with distinct keys, conversion is possible in linear time with bounds.
  • Validate that all input values are consumed to detect invalid sequences.
  • For general binary trees, combine pre-order with additional traversal data.
  • Choose recursive or iterative implementation based on expected tree depth.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.