一、题目描述
给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过也可能不穿过根结点。
二、C语言代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
// find the longest lenth staring with the root
// note: the p is not NULL
int findChildLenth(struct TreeNode *p, int* ret){
int lLenth = 0, rLenth = 0;
if(p->left)
lLenth = findChildLenth(p->left, ret) + 1;
if(p->right)
rLenth = findChildLenth(p->right, ret) + 1;
// calculate the maximum path lenth of any two nodes in the binary tree taking *p as root node
int lenth = lLenth + rLenth;
if (lenth > *ret)
*ret = lenth;
return lLenth >= rLenth ? lLenth : rLenth;
}
int diameterOfBinaryTree(struct TreeNode* root){
int ret = 0;
findChildLenth(root, &ret);
return ret;
}