求从二叉树根结点到指定结点p之间的路径c语言
时间: 2024-01-29 20:04:30 浏览: 93
假设二叉树的每个结点都有指向其左右子树的指针,可以使用递归的方式来求从根结点到指定结点p之间的路径。具体实现如下:
```c
#include <stdio.h>
// 定义二叉树结点结构体
typedef struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
// 查找从根结点到指定结点p之间的路径
int findPath(TreeNode* root, TreeNode* p, int path[], int len) {
if (root == NULL) {
return 0; // 未找到指定结点p,返回0
}
path[len++] = root->val; // 将当前结点加入路径中
if (root == p) {
return 1; // 找到指定结点p,返回1
}
if (findPath(root->left, p, path, len) || findPath(root->right, p, path, len)) {
return 1; // 在左右子树中找到指定结点p,返回1
}
return 0; // 未找到指定结点p,返回0
}
int main() {
// 创建一棵二叉树
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->val = 1;
root->left = (TreeNode*)malloc(sizeof(TreeNode));
root->left->val = 2;
root->left->left = NULL;
root->left->right = NULL;
root->right = (TreeNode*)malloc(sizeof(TreeNode));
root->right->val = 3;
root->right->left = (TreeNode*)malloc(sizeof(TreeNode));
root->right->left->val = 4;
root->right->left->left = NULL;
root->right->left->right = NULL;
root->right->right = NULL;
// 查找从根结点到指定结点的路径
TreeNode* p = root->right->left;
int path[100];
int len = 0;
int found = findPath(root, p, path, len);
if (found) {
printf("Path from root to node %d: ", p->val);
for (int i = 0; i < len; i++) {
printf("%d ", path[i]);
}
printf("\n");
} else {
printf("Node %d not found!\n", p->val);
}
return 0;
}
```
运行结果如下:
```
Path from root to node 4: 1 3 4
```
阅读全文