实际上是找左右子树的最大高度
C++ 代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int res;
int diameterOfBinaryTree(TreeNode* root) {
if(!root){
return 0;
}
dfs( root);
return res;
}
int dfs(TreeNode* root) {
if(!root){
return 0;
}
int left=dfs( root->left);
int right=dfs( root->right);
res=max(res,left+right);
return max(left,right)+1;
}
};