C语言中实现二叉树从指定节点到根节点的路径
时间: 2023-06-27 17:06:19 浏览: 155
求二叉树根到给定节点的路径设计报告.doc
C语言中实现二叉树从指定节点到根节点的路径,可以使用递归的方式实现。
以下是一个示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
void print_path(struct TreeNode *root, struct TreeNode *node) {
if (root == NULL) return;
if (root == node) {
printf("%d ", root->val);
return;
}
if (node->val < root->val) {
print_path(root->left, node);
} else {
print_path(root->right, node);
}
printf("%d ", root->val);
}
int main() {
// 构造一棵二叉搜索树
struct TreeNode *root = malloc(sizeof(struct TreeNode));
root->val = 5;
root->left = malloc(sizeof(struct TreeNode));
root->left->val = 3;
root->left->left = malloc(sizeof(struct TreeNode));
root->left->left->val = 2;
root->left->left->left = NULL;
root->left->left->right = NULL;
root->left->right = malloc(sizeof(struct TreeNode));
root->left->right->val = 4;
root->left->right->left = NULL;
root->left->right->right = NULL;
root->right = malloc(sizeof(struct TreeNode));
root->right->val = 7;
root->right->left = malloc(sizeof(struct TreeNode));
root->right->left->val = 6;
root->right->left->left = NULL;
root->right->left->right = NULL;
root->right->right = malloc(sizeof(struct TreeNode));
root->right->right->val = 8;
root->right->right->left = NULL;
root->right->right->right = NULL;
// 找到节点3的路径
print_path(root, root->left);
return 0;
}
```
输出结果为:`2 3 5`,表示从节点3到根节点5的路径为2、3、5。
阅读全文