# Tree Traversals

There are multiple ways to in which you can traverse a tree. In this article we will see these traversals in detail. If you are new to trees then I would recommend that you pay close attention to this article because you will be solving almost all the problems on tree by using one or more of these traversals.

Here we will discuss the recursive approach, we will have separate posts for Iterative or Non-recursive approach.

Traversals:

In every traversal we visit the tree in certain order. lets  discuss them in detail.

Preorder Traversal: ( Read about non-recursive approach of Preorder Traversal)

• Visit the root.
• Visit the left-subtree.
• Visit the right-subtree.

Inorder Traversal: ( Read about non-recursive approach of Inorder Traversal)

• Visit the left-subtree.
• Visit the root.
• Visit the right-subtree.

Postorder Traversal: ( Read about non-recursive approach of Postorder Traversal)

• Visit the right-subtree.
• Visit the left-subtree.
• Visit the root.

Code:

```Output:

Inorder Traversal:4 2 5 1 6 3 7
Preorder Traversal:1 2 4 5 3 6 7
Postorder Traversal:7 6 3 5 4 2 1
```

__________________________________________________
Top Companies Interview Questions..-

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________

### 4 Responses

1. Fuen Wu says:

As per the explanation ,it seems that the code for postOrderRecursive is not right ,it visit right subtree firstly.

• tutorialhorizon says:

Thanks Fuen, changed the explanation.

2. Shilpa says:

Post order traversal Algorithm is not correct.
It should be as follows-
1. Visit the left subtree
2. Visit the right subtree.
3. Then visit the root

• kosciCZ says:

+1, Fuen Wu propably meant that the code is wrong, the correct order of Post order indeed is Left Right Root.

This site uses Akismet to reduce spam. Learn how your comment data is processed.