# 543. Diameter of Binary Tree

## 1.問題

* 計算diameter: 任意兩node間最長的path

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LSCxXy1560aP5pHjkQh%2F-LSCyArerjOb_NpomPe0%2F%E8%9E%A2%E5%B9%95%E5%BF%AB%E7%85%A7%202018-11-26%20%E4%B8%8A%E5%8D%8811.03.05.png?alt=media\&token=1e93299b-66c3-4f9f-abae-dddcf7bcf253)

## 2.想法

* 參考104. Maximum Depth of Binary Tree
* 回傳值為 max(left path, right path) +1
* res = max(res, left path + right path)

## 3.程式碼

```
/**
 * 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;

    }
};
```
