用c语言写二叉树求根结点到叶子结点的最长距离
时间: 2023-10-16 22:07:19 浏览: 108
使用C语言求二叉树结点的最低公共祖先的方法
下面是用C语言实现二叉树求根节点到叶子节点的最长距离的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
int maxDepth(TreeNode *root) {
if (!root) {
return 0;
}
int left_depth = maxDepth(root->left);
int right_depth = maxDepth(root->right);
return left_depth > right_depth ? left_depth + 1 : right_depth + 1;
}
int maxDistance(TreeNode *root) {
if (!root) {
return 0;
}
int left_depth = maxDepth(root->left);
int right_depth = maxDepth(root->right);
int left_distance = maxDistance(root->left);
int right_distance = maxDistance(root->right);
return left_depth + right_depth > left_distance ? (left_depth + right_depth > right_distance ? left_depth + right_depth : right_distance) : (left_distance > right_distance ? left_distance : right_distance);
}
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 = (TreeNode *)malloc(sizeof(TreeNode));
root->left->right->val = 3;
root->left->right->left = NULL;
root->left->right->right = NULL;
root->right = (TreeNode *)malloc(sizeof(TreeNode));
root->right->val = 4;
root->right->left = (TreeNode *)malloc(sizeof(TreeNode));
root->right->left->val = 5;
root->right->left->left = NULL;
root->right->left->right = NULL;
root->right->right = NULL;
// 计算最长距离
int max_distance = maxDistance(root);
printf("The max distance of the binary tree is: %d\n", max_distance);
return 0;
}
```
其中,TreeNode是二叉树的节点结构体,maxDepth函数用于计算二叉树的深度,maxDistance函数用于计算二叉树的最长距离。main函数中创建了一个二叉树,并计算了它的最长距离。
阅读全文