/**
* 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 diameterOfBinaryTree(TreeNode* root) {
if(root == NULL){
return 0;
}
int res = 0;
getHeight(root, res);
return res;
}
int getHeight(TreeNode* root, int& res){
if(root == NULL) {
return 0;
}
int leftlength= getHeight(root->left,res);
int rightlength = getHeight(root->right,res);
//取在該點為root時的leftlength + rightlength的最大值
res = max(res, leftlength + rightlength);
//回傳max(左邊, 右邊)+1
return max(leftlength, rightlength) + 1;
}
};