Tree traversal algorithm in Python
Tree traversal (also known as tree search and walking the tree) is a form of graph traversal and refers to the process of visiting (e.g. retrieving, updating, or deleting) each node in a tree data structure, exactly once. Such traversals are classified by the order in which the nodes are visited. - Wikipedia
Tree traversal algorithms can be classified in the following two categories:
- Depth-First Search (DFS): It starts at the root node (selecting some arbitrary node as the root node in the case of a graph) and explores as far as possible along each branch before backtracking.
- Breadth-First Search (BFS): It starts at the tree’s root (selecting some arbitrary node as the root node in the case of a graph) and searches all nodes at the current depth level before moving on to the nodes at the next depth level.
Depth-First Search (DFS) algorithms have three variants:
- Preorder Traversal (current-left-right): Visit the current node before visiting any nodes inside left or right subtrees.
- Inorder Traversal (left-current-right): Visit the current node after visiting all nodes inside left subtree but before visiting any node within the right subtree.
- Postorder Traversal (left-right-current): Visit the current node after visiting all the nodes of left and right subtrees.
Breadth-First Search (BFS) Algorithm has one variant:
- Level Order Traversal: Visit nodes level-by-level and left-to-right fashion at the same level.
1 | class Node: |