543. 二叉树的直径

543. 二叉树的直径 - 力扣(LeetCode)

二刷

class Solution {
  int Diameter{};
  int Traverse(TreeNode *root) {
    if (!root)
      return 0;
    int DiaL = 0, DiaR = 0;
    if (root->left)
      DiaL = Traverse(root->left) + 1;
    if (root->right)
      DiaR = Traverse(root->right) + 1;
    Diameter = std::max(Diameter, DiaL + DiaR);
    return std::max(DiaL, DiaR);
  }

public:
  int diameterOfBinaryTree(TreeNode* root) {
    Traverse(root);
    return Diameter;
  }
};

哎我这个解法有点神奇的,我是按照模拟的思路来的,对路径和返程路径的分别处理有点像我之前做过的124. 二叉树中的最大路径和。但实际上这道题可以在求左右子树最大深度和的基础上修改。

不过说实话,那个 ans = 1; 和 return ans - 1; 其实看着有点迷惑的,我觉得不如我这个。

三刷

class Solution {
  int Diameter_{};
  int LocalDepth(TreeNode *root) {
    if (!root)
      return 0;
    int LDepth = LocalDepth(root->left);
    int RDepth = LocalDepth(root->right);
    Diameter_ = max(Diameter_, LDepth + RDepth);
    return max(LDepth, RDepth) + 1;
  }
public:
  int diameterOfBinaryTree(TreeNode* root) {
    LocalDepth(root);
    return Diameter_;
  }
};

这个比二刷写得更简洁,运用了104. 二叉树的最大深度官解当中的分配律,也就是「把\(+1\)提到外面来」的思路,不仅避免了多余的root->left和root->right条件判断,还省去了考虑LDepth和RDepth的共时性——这两个变量不能在计算Diameter_之前就默认已经\(+1\)——的思维负担。