二叉树问题中的求解二叉树所有路径的C语言代码
时间: 2024-03-14 19:23:46 浏览: 73
二叉树的C语言代码
以下是求解二叉树所有路径的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
void printPaths(struct TreeNode* root, int path[], int pathLen) {
if (!root) return;
path[pathLen++] = root->val;
if (!root->left && !root->right) {
for (int i = 0; i < pathLen; i++) {
printf("%d ", path[i]);
}
printf("\n");
} else {
printPaths(root->left, path, pathLen);
printPaths(root->right, path, pathLen);
}
}
int main() {
struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->val = 1;
root->left = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->left->val = 2;
root->left->left = NULL;
root->left->right = NULL;
root->right = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->right->val = 3;
root->right->left = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->right->left->val = 4;
root->right->left->left = NULL;
root->right->left->right = NULL;
root->right->right = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->right->right->val = 5;
root->right->right->left = NULL;
root->right->right->right = NULL;
int path[100];
printPaths(root, path, 0);
return 0;
}
```
这段代码实现了二叉树所有路径的打印,其中 `printPaths` 函数采用递归实现,每次递归时将当前节点的值加入到 `path` 数组中,并判断当前节点是否为叶子节点,若为叶子节点,则打印 `path` 数组中的所有值,否则继续递归遍历其左右子节点。 `main` 函数中构建了一个二叉树并调用 `printPaths` 函数进行遍历打印。
阅读全文