Skip to content

Latest commit

 

History

History
22 lines (20 loc) · 542 Bytes

File metadata and controls

22 lines (20 loc) · 542 Bytes
  • 经过某个根节点的最大直径为 左子树深度 + 右子树深度 + 1 - 1(题目定义的直径比路径长度少 1),遍历所有节点的直径,最大的即为结果
class Solution {
 public:
  int diameterOfBinaryTree(TreeNode* root) {
    int res = 0;
    depth(root, res);
    return res;
  }

  int depth(TreeNode* root, int& res) {
    if (!root) {
      return 0;
    }
    int l = depth(root->left, res);
    int r = depth(root->right, res);
    res = max(res, l + r);
    return 1 + max(l, r);
  }
};