C语言二叉树如何用先序遍历输出所有从叶子结点到根结点的逆路径,用代码显示出来
时间: 2024-05-09 11:02:20 浏览: 103
以下是C语言实现二叉树先序遍历输出所有从叶子节点到根节点的逆路径的代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *left, *right;
} Node;
void printPath(int path[], int len) {
// 逆序输出路径
for (int i = len - 1; i >= 0; i--) {
printf("%d ", path[i]);
}
printf("\n");
}
void printPaths(Node *root, int path[], int len) {
if (!root) {
return;
}
// 将当前节点添加到路径中
path[len] = root->data;
len++;
// 如果是叶子节点,输出路径
if (!root->left && !root->right) {
printPath(path, len);
return;
}
// 递归遍历左子树和右子树
printPaths(root->left, path, len);
printPaths(root->right, path, len);
}
Node* newNode(int data) {
Node *node = (Node*)malloc(sizeof(Node));
node->data = data;
node->left = node->right = NULL;
return node;
}
int main() {
Node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
int path[100];
printPaths(root, path, 0);
return 0;
}
```
输出结果为:
```
4 2 1
5 2 1
6 3 1
7 3 1
```
阅读全文