Personal understanding
DFS (depth-first search) and BFS similar, but also a simple graph search algorithm, its main idea is: each branch access to the deepest position, can not continue until so far.
Diagram
Now we want to find the path from node A to node G (not necessarily optimum), DFS following steps:
1, starting from the root node A, the node B of the selection path, and back, until it reaches the node E, can not go any further
2, then back to A, node C in the path selection, selecting the node E, has been found to E visited, and back to node C
3, the path select the node F, and back, until it reaches the node G
4, so that, A to node G of node path: A-> C-> F-> G
Fake code:
boolean DFS(Node root, Node target) {
Set<Node> vistised;
Stack<Node> stack;
add root node to vistised;
add root node to stack;
while(stack is not empty) {
Node cur = top node of stack;
if (cur == target) return true;
for (Node next : child nodes of cur) {
if (next is not visisted) {
add next to vistised;
add next to stack;
}
}
remove cur from stack;
}
return false;
}
Stay button corresponding to the example
https://leetcode-cn.com/problems/binary-tree-inorder-traversal/
https://leetcode-cn.com/problems/decode-string/
https://leetcode-cn.com/problems/keys-and-rooms/