C语言版输出二叉树的逆路径
时间: 2024-05-01 07:19:11 浏览: 71
二叉树的逆路径指的是从叶子节点到根节点的路径。可以通过递归的方式,先遍历右子树再遍历左子树,输出节点值即可。以下是一个示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
void printReversePath(struct TreeNode* root) {
if (root == NULL) return;
if (root->left == NULL && root->right == NULL) {
printf("%d ", root->val);
return;
}
printReversePath(root->right);
printReversePath(root->left);
printf("%d ", root->val);
}
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 = NULL;
root->right->right = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->right->right->val = 4;
root->right->right->left = NULL;
root->right->right->right = NULL;
printf("The reverse path is: ");
printReversePath(root);
return 0;
}
```
输出结果为:4 3 1。
阅读全文