深度优先遍历(Depth First Search)简称DFS,是一种图形搜索算法,它从一个起点开始,沿着图的深度方向不断探索,直到不能再继续为止,然后回溯到上一个节点,继续探索其他分支,直到遍历完所有的节点为止。你可以把它想象成一个迷宫探险者,每次选择一条路走到底,如果遇到死胡同就返回上一步,换另一条路继续前进。
树是一种特殊的图,所以树也可以用DFS来遍历。树的DFS有三种常见的顺序:前序、中序和后序。前序遍历是先访问当前节点,再访问左子树和右子树;中序遍历是先访问左子树,再访问当前节点和右子树;后序遍历是先访问左子树和右子树,再访问当前节点。
用C++实现的话,可以用递归或者栈来模拟DFS的过程。递归是自动使用系统栈来存储函数调用信息;栈是手动使用数据结构来存储节点信息。每次从栈中取出一个节点,并将其未被访问过且可达的相邻节点压入栈中。重复这个过程直到栈为空或者找到目标为止。
代码如下:
#include <iostream>
#include <stack>
using namespace std;
//定义二叉树结构体
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
//定义图结构体
struct GraphNode {
int val;
vector<GraphNode*> neighbors;
GraphNode(int x) : val(x) {}
};
//定义函数实现二叉树的前序遍历
void preorder(TreeNode* root) {
if (root == NULL) return; //空指针直接返回
cout << root->val << " "; //打印当前节点值
preorder(root->left); //递归遍历左子树
preorder(root->right); //递归遍历右子树
}
//定义函数实现二叉树的中序遍历
void inorder(TreeNode* root) {
if (root == NULL) return; //空指针直接返回
inorder(root->left); //递归遍历左子树
cout << root->val << " "; //打印当前节点值
Source: (1) Algorithm-Learning/搜索与图论.md at main · konanl/Algorithm-Learning. https://github.com/konanl/Algorithm-Learning/blob/main/AcWing-Class/%E7%AE%97%E6%B3%95%E5%9F%BA%E7%A1%80%E8%AF%BE/%E6%90%9C%E7%B4%A2%E4%B8%8E%E5%9B%BE%E8%AE%BA.md .
(2) CVPR 2020 论文_woha1yo的博客-程序员秘密 - 程序员秘密. https://cxymm.net/article/woha1yo/104630958 .
(3) haiyang/README.md at master · birdhumming/haiyang · GitHub. https://github.com/birdhumming/haiyang/blob/master/README.md .
(4) GitHub - shinezzz/AcWingBasicAlgorithmCourse: ACWing 算法基础课. https://github.com/shinezzz/AcWingBasicAlgorithmCourse .
(5) C docs - get started, tutorials, reference. | Microsoft Learn. https://learn.microsoft.com/en-us/cpp/cpp/?view=msvc-170 .
(6) Microsoft C/C Documentation | Microsoft Learn. https://learn.microsoft.com/en-us/cpp/?view=msvc-170 .