###### tags: `LeetCode` `Tree` `Recursion` `Easy` # LeetCode #543 [Diameter of Binary Tree](https://leetcode.com/problems/diameter-of-binary-tree/) ### (Easy) 給定一棵二元樹,你需要計算它的直徑長度。一棵二元樹的直徑長度是任意兩個結點路徑長度中的最大值。這條路徑可能穿過也可能不穿過根結點。 --- 與#124類似, 但這題更為簡單, 只要計算路徑長(也就是說每次都+1), 要注意的點還是一樣, 計算最大路徑長的時候是左路徑+右路徑+節點; 但回傳時只能從左右子樹中路徑較長的一邊中選擇, 並加上節點回傳。此外, 由於是計算路徑, 而兩點形成一邊, 所以最後回傳的值需要-1(節點數-1為路徑邊長)。 做#124之前應該先做這題更為恰當。 --- ``` class Solution { public: int pathSum=INT_MIN; int diameterOfBinaryTree(TreeNode* root) { count(root); return pathSum-1; } int count(TreeNode* node){ if(!node)return 0; int l=count(node->left); int r=count(node->right); pathSum=max(pathSum, l+r+1); return max(l,r)+1; } }; ```
×
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