Pre, Post, Inorder in one traversal
Pattern: Traversals
Each node is met three times on a depth-first walk: before its left subtree, between its subtrees, and after its right subtree. Keep (node, count) pairs on a stack; count 1 records preorder, 2 records inorder, 3 records postorder.
The problem
Return the preorder, inorder and postorder of a binary tree, in that order, from a single walk. [1, 2, 3] gives
[[1, 2, 3], [2, 1, 3], [2, 3, 1]]. Trees in the examples are written in level order, with null for a missing child, as on LeetCode.
Think first
- How many times does a depth-first walk pass each node?
- What happens at each of those moments?
- How can a stack remember which moment is next?
Hints
Brute force, and why it fails
Run the three traversals separately: still O(n), but three passes.
The key insight
Tagging each stack entry with its visit count turns one walk into all three orders.
Dry run
| pre | 1 |
|---|
Tree [1, 2, 3]. Push (1, 1). Pop it: preorder 1; push (1, 2) and (2, 1).
The plan
stack = [(root, 1)]
while stack:
(n, c) = pop
c == 1: pre += n; push (n, 2); push (n.left, 1) if any
c == 2: in += n; push (n, 3); push (n.right, 1) if any
c == 3: post += n
Complexity
- Time
O(n)- Space
O(h)
Each node is pushed three times.
Edge cases
- Empty tree: an empty list.
- One node.
- A tree that is a single long chain: the stack grows to n.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public List<List<Integer>> treeTraversal(TreeNode root) {
List<Integer> pre = new ArrayList<>(), in = new ArrayList<>(), post = new ArrayList<>();
if (root != null) {
Deque<Object[]> stack = new ArrayDeque<>(); // {node, how many times we have seen it}
stack.push(new Object[]{root, 1});
while (!stack.isEmpty()) {
Object[] top = stack.pop();
TreeNode node = (TreeNode) top[0];
int state = (Integer) top[1];
if (state == 1) { // first visit: preorder, then go left
pre.add(node.val);
stack.push(new Object[]{node, 2});
if (node.left != null) stack.push(new Object[]{node.left, 1});
} else if (state == 2) { // back from the left: inorder, then go right
in.add(node.val);
stack.push(new Object[]{node, 3});
if (node.right != null) stack.push(new Object[]{node.right, 1});
} else { // back from the right: postorder
post.add(node.val);
}
}
}
return Arrays.asList(pre, in, post);
}
}C++
class Solution {
public:
vector<vector<int>> treeTraversal(TreeNode* root) {
vector<int> pre, in, post;
stack<pair<TreeNode*, int>> st; // {node, how many times we have seen it}
if (root != NULL) st.push(make_pair(root, 1));
while (!st.empty()) {
pair<TreeNode*, int> top = st.top();
st.pop();
TreeNode* node = top.first;
if (top.second == 1) { // first visit: preorder, then go left
pre.push_back(node->val);
st.push(make_pair(node, 2));
if (node->left != NULL) st.push(make_pair(node->left, 1));
} else if (top.second == 2) { // back from the left: inorder, then go right
in.push_back(node->val);
st.push(make_pair(node, 3));
if (node->right != NULL) st.push(make_pair(node->right, 1));
} else { // back from the right: postorder
post.push_back(node->val);
}
}
return vector<vector<int>>{pre, in, post};
}
};Python
class Solution:
def treeTraversal(self, root) -> list[list[int]]:
pre, ino, post = [], [], []
stack = [(root, 1)] if root else [] # (node, how many times we have seen it)
while stack:
node, state = stack.pop()
if state == 1: # first visit: preorder, then go left
pre.append(node.val)
stack.append((node, 2))
if node.left:
stack.append((node.left, 1))
elif state == 2: # back from the left: inorder, then go right
ino.append(node.val)
stack.append((node, 3))
if node.right:
stack.append((node.right, 1))
else: # back from the right: postorder
post.append(node.val)
return [pre, ino, post]Common mistakes
- Pushing the child before re-pushing the node with the next count.
- Mixing up the order of the three lists in the answer.