写一段C语言代码实现树的DFS
时间: 2023-12-19 15:53:57 浏览: 83
数据结构与算法代码,c语言实现
假设我们有如下树结构:
```
1
/ | \
2 3 4
/ \ / \
5 6 7 8
```
我们可以使用递归的方式来实现DFS:
```c
#include <stdio.h>
#define MAX_NODE_NUM 100
typedef struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
// 创建树结构
TreeNode* createTree() {
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->val = 1;
root->left = (TreeNode*)malloc(sizeof(TreeNode));
root->left->val = 2;
root->left->left = (TreeNode*)malloc(sizeof(TreeNode));
root->left->left->val = 5;
root->left->left->left = NULL;
root->left->left->right = NULL;
root->left->right = (TreeNode*)malloc(sizeof(TreeNode));
root->left->right->val = 6;
root->left->right->left = NULL;
root->left->right->right = NULL;
root->right = (TreeNode*)malloc(sizeof(TreeNode));
root->right->val = 4;
root->right->left = (TreeNode*)malloc(sizeof(TreeNode));
root->right->left->val = 7;
root->right->left->left = NULL;
root->right->left->right = NULL;
root->right->right = (TreeNode*)malloc(sizeof(TreeNode));
root->right->right->val = 8;
root->right->right->left = NULL;
root->right->right->right = NULL;
return root;
}
// DFS遍历树
void dfs(TreeNode* node, int* visited) {
if (node == NULL) {
return;
}
visited[node->val] = 1;
printf("%d ", node->val);
dfs(node->left, visited);
dfs(node->right, visited);
}
int main() {
int visited[MAX_NODE_NUM] = {0};
TreeNode* root = createTree();
dfs(root, visited);
return 0;
}
```
输出结果为:
```
1 2 5 6 3 4 7 8
```
其中,`visited`数组用于记录每个节点是否已经被遍历过,防止重复遍历。在这里我们使用了一个简单的方法,即将节点的值作为数组的下标,将对应的值设为1表示已经遍历过。在实际应用中,可能需要使用更加复杂的方法来记录节点的遍历情况。
阅读全文