543. Diameter of Binary Tree Posted on 2020-11-29 Edited on 2021-03-08 In LeetCode Disqus: Symbols count in article: 527 Reading time ≈ 1 mins. postorder O(n) 跟124. Binary Tree Maximum Path Sum思路基本一致 12345678910111213141516171819202122232425/** * 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) { dfs(root); return res; } int dfs(TreeNode *root) { // 返回以root为根的最长链有几个结点 if (!root) return 0; int l = dfs(root->left), r = dfs(root->right); res = max(res, l + r); // 人家问的是边不是点,不要加1 return max(l, r) + 1; } int res = 0;};