---
# System prepended metadata

title: 'Leetcode 543: Diameeter of Binary Tree (已解決)'

---

# Leetcode 543: Diameeter of Binary Tree (已解決)

```cpp=
class Solution {
public:

    int maxdepth = 0; //用來記錄最大深度
    int max_diameter(TreeNode* root){
        if(!root)
            return 0;
        int left = max_diameter(root->left);
        int right = max_diameter(root->right);

        maxdepth = max(maxdepth,left+right);
        //此行最後會比較單邊最大深度和左右子樹相加長度

        return max(left,right)+1;
    }

    int diameterOfBinaryTree(TreeNode* root) {

        if(!root)
            return 0;
        max_diameter(root);
      
        return maxdepth;
    }


};
```

結果 : 

https://leetcode.com/problems/diameter-of-binary-tree/submissions/847216204/

