Tree definition and traversal
What is tree data structure?
The tree is a type of data structure that represents data hierarchically. Trees are a collection of nodes with a root node, and every node is connected to its parent node using edges. Every node has only one parent in a tree but can have multiple child nodes. The types of trees are as follows :
- General tree: The tree with no restriction of the number of child nodes is known as the general tree.
- Binary tree: A binary tree is a tree in which a node can have at most two nodes.
Traversal in tree and its types
Traversal is a way to visit each node in a tree. There are three main types of traversal in the tree data structure.
- In-order traversal: The pointer visits each node in non-decreasing order in the in-order traversal method.
Algorithm
- Traverse to left subtree.
- Visit the root node.
- Traverse to right subtree.
- Pre-order traversal: Pre Order method creates a copy of the tree which it is traversing.
Algorithm
- Visit the root node.
- Traverse to left subtree.
- Traverse to right subtree.
- Post-order traversal: Post-order is to delete the tree while traversing.
Algorithm
- Traverse to left subtree.
- Traverse to right subtree.
- Visit the root node.