# 543. Diameter of Binary Tree

## 1.問題

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

![](/files/-LSCyArerjOb_NpomPe0)

## 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;

    }
};
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jenhsuan.gitbook.io/algorithm/leetcode/543.-diameter-of-binary-tree.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
