最大直径存在下面三种情况:
1,通过ROOT节点: 右子树的最大深度+左子树的最大深度
2,不通过ROOT节点,存在在于两个子树中的一个
计算3中情况的最大值
int depth(struct TreeNode *root)
{
if(root == NULL)
return 0;
int l = depth(root->left);
int r = depth(root->right);
return (l>r?l:r)+1;
}
int diameterOfBinaryTree(struct TreeNode* root) {
if(root == NULL)
return 0;
int sum = depth(root->right)+depth(root->left);
int l = diameterOfBinaryTree(root->left);
int r = diameterOfBinaryTree(root->right);
int sum2 = (l>r?l:r);
return sum2>sum?sum2:sum;
}