Tree Traversals
What is a Tree?
A Data Structure is a way to organize and store data using a Computer Program. We store data in a certain way to suit the needs of the Program that we are writing.
A Tree is a special type of Graph Data Structure where all the nodes originate either directly or indirectly from exactly one node, called the root node.
What is a Tree Traversal?
Tree traversal is the process of visiting each node of the tree data structure.
Why do we need to traverse a Tree?
We traverse a Tree in order to find and process the information that is stored in a tree data structure.
What are the different types of Tree Traversals?
Like Graph Traversal there are two basic types of Tree Traversals:
- Breadth First Search or Level Order Traversal
- Depth First Search
- Preorder Traversal - Root, Left, Right
- Inorder Traversal - Left, Root, Right
- Postorder Traversal- Left, Right, Root
Algorithm for Preorder Traversal:
- Visit Root node.
- Visit Left node or Left subtree.
- Visit Right node or Right subtree.
Algorithm for Inorder Traversal:
- Visit Left node or Left subtree.
- Visit Root node.
- Visit Right node or Right subtree.
Algorithm for Postorder Traversal:
- Visit Left node or Left subtree.
- Visit Right node or Right subtree.
- Visit Root node.
The youtube tutorial below explains this concept really well: