用c语言输出树中从根结点到所有叶结点的路径
时间: 2023-12-29 21:05:03 浏览: 78
输出树的根节点到叶子节点的所有路径
4星 · 用户满意度95%
以下是用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 == NULL) {
return;
}
path[pathLen] = root->val;
pathLen++;
if (root->left == NULL && root->right == NULL) {
for (int i = 0; i < pathLen; i++) {
printf("%d", path[i]);
if (i != pathLen - 1) {
printf("->");
}
}
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;
}
```
阅读全文