c语言输出二叉树最长路径所有结点
时间: 2023-08-18 12:14:05 浏览: 110
二叉树上结点的路径
4星 · 用户满意度95%
实现这个功能需要对二叉树进行遍历,找到最长路径上的所有节点。以下是一个基于递归的实现:
```c
#include <stdio.h>
#include <stdlib.h>
// 二叉树结构体
typedef struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
// 计算树的高度
int getHeight(TreeNode* root) {
if (root == NULL) {
return 0;
}
int leftHeight = getHeight(root->left);
int rightHeight = getHeight(root->right);
return (leftHeight > rightHeight ? leftHeight : rightHeight) + 1;
}
// 打印从根节点到叶子节点的路径
void printPath(int path[], int len) {
for (int i = 0; i < len; i++) {
printf("%d ", path[i]);
}
printf("\n");
}
// 在树中查找最长路径
void findLongestPath(TreeNode* root, int path[], int len) {
if (root == NULL) {
return;
}
path[len++] = root->val;
if (root->left == NULL && root->right == NULL) {
printPath(path, len);
} else {
findLongestPath(root->left, path, len);
findLongestPath(root->right, path, len);
}
}
int main() {
// 构造一个二叉树
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->val = 1;
root->left = (TreeNode*)malloc(sizeof(TreeNode));
root->left->val = 2;
root->right = (TreeNode*)malloc(sizeof(TreeNode));
root->right->val = 3;
root->left->left = (TreeNode*)malloc(sizeof(TreeNode));
root->left->left->val = 4;
root->left->right = (TreeNode*)malloc(sizeof(TreeNode));
root->left->right->val = 5;
root->right->left = (TreeNode*)malloc(sizeof(TreeNode));
root->right->left->val = 6;
root->right->right = (TreeNode*)malloc(sizeof(TreeNode));
root->right->right->val = 7;
root->left->left->left = (TreeNode*)malloc(sizeof(TreeNode));
root->left->left->left->val = 8;
// 计算树的高度
int height = getHeight(root);
// 分配存放路径的数组
int* path = (int*)malloc(height * sizeof(int));
// 查找最长路径
findLongestPath(root, path, 0);
// 释放内存
free(path);
free(root->left->left->left);
free(root->right->right);
free(root->right->left);
free(root->left->right);
free(root->left->left);
free(root->right);
free(root->left);
free(root);
return 0;
}
```
输出结果为:
```
1 2 4 8
1 2 5
1 3 6
1 3 7
```
阅读全文