5433: 数据结构实验:二叉树的直径
时间限制(普通/Java):1000MS/3000MS 内存限制:65536KByte
总提交:60 测试通过:21
总提交:60 测试通过:21
描述
求一棵二叉树的直径,即任意两个结点之间的路径长度最大值,路径可以经过根结点,父子节点之间的路径长度定义为1。
二叉树节点定义如下:
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
题目部分代码已经完成,您只需要补充并提交以下函数:
int diameterOfBinaryTree(struct TreeNode* root);
输入
输入为若干个整数(不超过512)表示一棵二叉树顺序表示时的结点元素值,其中0表示二叉树对应结点为空。输入以-1结束。
输出
输出二叉树的直径。
样例输入
1 2 3 4 5 -1
样例输出
3
题目来源
#include <stdio.h> #include <stdlib.h> struct TreeNode { int val; struct TreeNode *left,*right; }; struct TreeNode a[520]; struct TreeNode* Creat(struct TreeNode* root) { int k=0,i,j,n; while(scanf("%d",&n),n!=-1) a[k++].val=n; for(i=0,j=1;i<k;i++,j++) { if(i+j>=k||a[i+j].val==0) a[i].left=NULL; else a[i].left=&a[i+j]; if(i+j+1>=k||a[i+j+1].val==0) a[i].right=NULL; else a[i].right=&a[i+j+1]; } return &a[0]; } int maxn=0; int depth(struct TreeNode* root) { if(!root) return 0; int ls=depth(root->left); int rs=depth(root->right); return ls>rs?(ls+1):(rs+1); } void dfs(struct TreeNode* root) { if(root) { int n=depth(root->left),m=depth(root->right); if(n+m>maxn) maxn=n+m; dfs(root->left); dfs(root->right); } } int diameterOfBinaryTree(struct TreeNode* root) { dfs(root); return maxn; } int main() { struct TreeNode* root=NULL; root=Creat(root); printf("%d\n",diameterOfBinaryTree(root)); return 0; }