Depth First Search (DFS)
About
Is a Graph or Tree traversal algorithm used to explore nodes and edges. It can also be used as a Search algorithm.
Preserves the shape of the traversal.
It uses Stack to store nodes in order.
How it Works
DFS explores entire branches (goes all the way to the leafs) first before moving to neighbor branches.
In more detail
In Graphs, you must also mark visited nodes, so that they don't get pushed again to the Stack.
In BST where you garantee order, you may add additional conditions to prioritize going left or right first, depending on the needle value.
At start node
N:Push
Nto theStack.Push
N'schildren to theStack.Process
Nand remove it from theStack.
Pop next node
N(last) fromStack:Push its children to the
Stack.Process node
N, and remove it fromStack.
Repeat
2.until all nodes were processed.
Last updated