问题描述:
给定一颗二叉树,你需要计算它的直径长度。
问题分析:
本题是一个典型的二叉树递归算法考察。我们需要分别计算出最长的左右子树,然后对最长进行返回。
class Solution{
int Maxlen = 0;
public:
int diameterOfBinaryTree(TreeNode* root)
{
helper(root); //自身函数没办法完成递归,从而采用DFS函数来求解
return len;
}
int helper(TreeNode* root){
if(root==nullptr) return 0;
int left = helper(root->left);
int right = helper(root->right);
Maxlen = max(Maxlen,right+left); //总是保存最大值
return max(left,right)+1;
}
};