Binary Tree Postorder Traversal without Recursion

 In this tutorial, I am going to discuss binary tree postorder traversal. How to implement binary tree postorder traversal with and without recursion.

Given the root of a binary tree, write a code to return the postorder traversal of its node’s values.

Binary Tree Postorder Traversal without Recursion

A binary tree can be traversed either using DFS (inorder, preorder, and postorder) or BFS (level order) traversal technique.

In my previous tutorials, I have already explained inorder, preorder, and level order traversal. In this tutorial, let’s learn how to implement postorder traversal with and without recursion.

Preorder traversal without recursion

Inorder traversal without recursion

Binary tree level order traversal

Postorder Traversal

In postorder traversal –

i) First, we traverse the left subtree of root in postorder.

ii) Then we traverse the right subtree of root in postorder.

iii) Finally we visit root.

Binary Tree Postorder Traversal using Recursion

Implementing postorder traversal using recursion is very straightforward. In postorder traversal, we have to visit both the left and right subtrees before visiting the node.

Here is the implementation.


i) Recursively call postorderHelper for the left node
ii) Recursively call postorderHelper for the right node. iii)Add the node value in a result list.

Binary Tree Postorder Traversal without Recursion

In this example, we are doing iterative postorder traversal using two stacks. Here are the steps.

  1. Declare two stacks. Push root node to the first stack.
  2. Run a while loop while first stack is not empty
    2.1 Pop a node from first stack and push it to second stack
    2.2 Push left and right children of the popped node to the first stack.
  3. After complete traversal, print the node values of a second stack.

The time complexity is O(n) and its space complexity is also O(n).

Iterative postorder traversal

Programming video tutorials

Tagged , , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.