In Linked Representation of Binary Tree, there are 3 ways to traverse: -
In PreOrder Traversal, the root node is visited first, then the left subtree, and finally the right subtree.
Order : Root
→ Left Subtree
→ Right Subtree
From the above image data: -
1
2
4
5
3
6
7
Output: 1 2 4 5 3 6 7
Look at the structure above, In PreOrder Traversal first, we have to visit the root node
, then the Left Subtree
, and keep visiting Left Subtree
and repeat the process until it has No Node
, then go back from there and visit Right Subtree
and again follow the same process.
In InOrder
Traversal, the left subtree is visited first, then the root node, and finally the right subtree.
Order : Left Subtree
→ Root
→ Right Subtree
From the above image data: -
4
2
5
1
6
3
7
Output: 4 2 5 1 6 3 7
In InOrder
Traversal first, we have to keep visiting Left Subtree
and repeat the process until it has No Node
and then go back to the root node
after that, visit the Right Subtree
and again follow the same process.
In PostOrder
Traversal, the left subtree is visited first, then the right subtree, and finally the root node.
Order : Left Subtree
→ Right Subtree
→ Root
From the above image data: -
4
5
2
6
7
3
1
Output: 4 5 2 6 7 3 1
In PostOrder
Traversal first, we have to keep visiting Left Subtree
and repeat the process until it has No Node. Then go to Right Subtree and again repeat the process and when there is No Node, visit the root node
.
In these tricks, We draw a line from the root node that travels near every node and draw an arrow in every node that cuts the line according to the order.
You will understand from the below images.
In PreOrder
, We have to Draw an arrow in Left Direction from the Node that cuts the line.
By following the line from the root node: -
Result: 1 2 4 5 3 6 7
In InOrder
, We have to Draw an arrow in Bottom Direction from the Node that cuts the line.
By following the line from the root node: -
Result: 4 2 5 1 6 3 7
In PostOrder
, We have to Draw an arrow in the Right Direction from the Node that cuts the line.
By following the line from the root node: -
Result: 4 5 2 6 7 3 1