Search
Search
Breath First Search
Breadth First Search (BFS) algorithm traverses a graph in a breadthward motion and uses a queue to remember to get the next vertex to start a search, when a dead end occurs in any iteration.
As in the example given above, BFS algorithm traverses from A to B to E to F first then to C and G lastly to D. It employs the following rules:
- Visit the adjacent unvisited vertex. Mark it as visited. Display it. Insert it in a queue.
- If no adjacent vertex is found, remove the first vertex from the queue, and set this vertex as the head.
- Repeat Rule 1 and Rule 2 until the queue is empty.
1 | class BinaryTreeNode: |
Depth First Search
Depth First Search (DFS) algorithm traverses a graph in a depthward motion and uses a stack to remember to get the next vertex to start a search, when a dead end occurs in any iteration.
As in the example given above, DFS algorithm traverses from S to A to D to G to E to B first, then to F and lastly to C. It employs the following rules:
- Visit the adjacent unvisited vertex. Mark it as visited. Display it. Push it in a stack.
- If no adjacent vertex is found, pop up a vertex from the stack. (It will pop up all the vertices from the stack, which do not have adjacent vertices.)
- Repeat Rule 1 and Rule 2 until the stack is empty.
1 | def dfs(tree): |
Reference
https://www.tutorialspoint.com/data_structures_algorithms/depth_first_traversal.htm