# 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/
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up