leetcode

543.二叉树的直径

力扣链接

class Solution {
public:
    int traversal(TreeNode* root, int&res){
      if (!root) return 0; // 访问到空节点了,返回0
      int left = traversal(root->left, res); // 左儿子为根的子树的深度
      int right = traversal(root->right, res); // 右儿子为根的子树的深度
      res = std::max(res, left + right); // 比较 更新不同根结点的最长路径
      return std::max(left, right) + 1; // 返回该节点为根的子树的深度 深度指节点数,直径指路径
    }

    int diameterOfBinaryTree(TreeNode* root) { 
      int res = 0;
      traversal(root, res);
      return res;
    }
};