a Tree Traversal is the process of visiting (reading or processing) each node in a tree data structure exactly once.
Unlike linear data structures (like Arrays or Linked Lists) which can only be read in one sequential logical way, trees are non-linear. Therefore, they can be traversed in multiple ways. The most common tree traversals are categorized under Depth-First Search (DFS), which includes three main methods:
-
Pre-order Traversal
-
In-order Traversal
-
Post-order Traversal
2. Pre-order Traversal (Root $\rightarrow$ Left $\rightarrow$ Right)
In a Pre-order traversal, the root node is visited first, followed by the left subtree, and finally the right subtree.
-
Algorithm / Steps:
-
Visit the Root node.
-
Recursively traverse the Left subtree.
-
Recursively traverse the Right subtree.
-
-
Primary Application: It is used to create a "clone" or exact copy of the tree. It is also used to evaluate Prefix expressions.
3. In-order Traversal (Left $\rightarrow$ Root $\rightarrow$ Right)
In an In-order traversal, the left subtree is visited first, then the root node, and finally the right subtree.
-
Algorithm / Steps:
-
Recursively traverse the Left subtree.
-
Visit the Root node.
-
Recursively traverse the Right subtree.
-
-
Primary Application: In a Binary Search Tree (BST), performing an In-order traversal always returns the values in sorted (ascending) order.
4. Post-order Traversal (Left $\rightarrow$ Right $\rightarrow$ Root)
In a Post-order traversal, the left subtree is visited first, then the right subtree, and the root node is visited at the very end.
-
Algorithm / Steps:
-
Recursively traverse the Left subtree.
-
Recursively traverse the Right subtree.
-
Visit the Root node.
-
-
Primary Application: It is used to delete the tree from memory (because you must delete the children before you delete the parent node). It is also used to evaluate Postfix expressions.





