求二叉树指定结点到根的路径c语言,建立二叉树并求指定结点路径.doc
时间: 2024-03-07 19:46:39 浏览: 55
好的,以下是建立二叉树并求指定结点路径的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
struct TreeNode* createTree() {
int val;
scanf("%d", &val);
if (val == -1) return NULL;
struct TreeNode *root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->val = val;
root->left = createTree();
root->right = createTree();
return root;
}
int findPath(struct TreeNode* root, int target, int* path) {
if (!root) return 0;
if (root->val == target) {
*path++ = root->val;
return 1;
}
if (findPath(root->left, target, path+1) || findPath(root->right, target, path+1)) {
*path++ = root->val;
return 1;
}
return 0;
}
int main() {
struct TreeNode *root = createTree();
int target;
scanf("%d", &target);
int path[1000] = {0};
int found = findPath(root, target, path);
if (found) {
for (int i = 0; path[i]; i++) {
printf("%d ", path[i]);
}
printf("\n");
} else {
printf("Not found!\n");
}
return 0;
}
```
这段代码首先通过递归方式创建一个二叉树,然后输入要查找的结点值,接着调用findPath函数查找该结点并将路径存储在path数组中,最后输出路径。
请注意,这段代码没有考虑二叉树中可能存在重复结点值的情况。
阅读全文