做题链接: 二叉树的直径.
建议大家对照着我的手写过程和代码理解。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int ans;
int maxDepth(struct TreeNode *root)
{
if(root == NULL) return 0;
int left = maxDepth(root->left);
int right = maxDepth(root->right);
ans = ans > (left+right+1) ? ans : (left+right+1);
return ( (left > right ? left : right) + 1 );
}
int diameterOfBinaryTree(struct TreeNode* root){
ans = 1;
if(root == NULL) return 0;
maxDepth(root);
return ans-1;
}