给你一棵二叉树的根节点,返回该树的 直径 。
二叉树的 直径 是指树中任意两个节点之间最长路径的 长度 。这条路径可能经过也可能不经过根节点 root 。两节点之间路径的长度由它们之间边数表示。
针对此题很容易想到递归的计算方式,但是在构思递归的时候这边有两个难点需要注意:
难点一:
如何将每个节点的最大路径记录下来并作比较?
每个节点的最大路径长度为左边的最大路径长度加上右边的最大路径长度
max = fmax(Count_left+Count_right,max);
难点二:
如何计算左边和右边的最大路径长度?
每个节点的最大路径长度为深度
return fmax(Count_left+1,Count_right+1);
综上所述:max作为一个全局变量接收最大值
int max = 0;
int tempBinaryTree(struct TreeNode* root){
if(root==NULL)
{
return 0;
}
int Count_left = tempBinaryTree(root->left);
int Count_right =tempBinaryTree(root->right);
max = fmax(Count_left+Count_right,max);
return fmax(Count_left+1,Count_right+1);
}
int diameterOfBinaryTree(struct TreeNode* root){
max=0;
tempBinaryTree(root);
return max;
}