# Iterative Post-Order Traversal

Hard

Implement an iterative, post-order traversal of a given binary tree, return the list of keys of each node in the tree as it is post-order traversed.

**Examples**

&#x20;       5

&#x20;     /    \\

&#x20;   3        8

&#x20; /   \        \\

1      4        11

Post-order traversal is \[1, 4, 3, 11, 8, 5]

**Corner Cases**

* What if the given binary tree is null? Return an empty list in this case.

**How is the binary tree represented?**

We use the level order traversal sequence with a special symbol "#" denoting the null node.

**For Example:**

The sequence \[1, 2, 3, #, #, 4] represents the following binary tree:

&#x20;   1

&#x20; /   \\

&#x20;2     3

&#x20;     /

&#x20;   4

Solution: self, left, right check, then flip

since the goal is to obtain nodes in order of

1. left child
2. right child
3. self

We use a stack to perform&#x20;

1. poll self
2. offer left child
3. offer right child

Since stacks are LIFO, this will result in&#x20;

1. add self&#x20;
2. add right
3. add left

Finally reverse the results

```java
public class Solution {
  public List<Integer> postOrder(TreeNode root) {
    List<Integer> result = new ArrayList<>();
    if (root == null){
      return result;
    }
    Deque<TreeNode> preOrder = new LinkedList<>();
    preOrder.offerFirst(root);
    while(!preOrder.isEmpty()){
      TreeNode current = preOrder.pollFirst();
      result.add(current.key);
      if (current.left != null){
        preOrder.offerFirst(current.left);
      }
      if (current.right != null){
        preOrder.offerFirst(current.right);
      }
    }
    Collections.reverse(result);
    return result;
  }


}

```

TC: O(N)

SC: O(N)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://llssff.gitbook.io/coding-problems/tree-traversal/iterative-post-order-traversal.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
