# 543. Diameter of Binary Tree

Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longestpath between any two nodes in a tree. This path may or may not pass through the root.

Example:
Given a binary tree

``````          1
/ \
2   3
/ \
4   5
``````

Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].

Note: The length of path between two nodes is represented by the number of edges between them.

``````class Solution {
public:
int diameterOfBinaryTree(TreeNode* root) {
if (!root) return 0;
int res = getHeight(root->left) + getHeight(root->right);
return max(res, max(diameterOfBinaryTree(root->left), diameterOfBinaryTree(root->right)));
}
int getHeight(TreeNode* node) {
if (!node) return 0;
if (m.count(node)) return m[node];
int h = 1 + max(getHeight(node->left), getHeight(node->right));
return m[node] = h;
}

private:
unordered_map<TreeNode*, int> m;
};
``````

``````class Solution {
public:
int diameterOfBinaryTree(TreeNode* root) {
int res = 0;
maxDepth(root, res);
return res;
}
int maxDepth(TreeNode* node, int& res) {
if (!node) return 0;
int left = maxDepth(node->left, res);
int right = maxDepth(node->right, res);
res = max(res, left + right);
return max(left, right) + 1;
}
};
``````

``````class Solution {
public:
int diameterOfBinaryTree(TreeNode* root) {
int res = 0;
maxDepth(root, res);
return res;
}
int maxDepth(TreeNode* node, int& res) {
if (!node) return 0;
if (m.count(node)) return m[node];
int left = maxDepth(node->left, res);
int right = maxDepth(node->right, res);
res = max(res, left + right);
return m[node] = (max(left, right) + 1);
}

private:
unordered_map<TreeNode*, int> m;
};
``````

https://leetcode.com/problems/diameter-of-binary-tree/description/

https://leetcode.com/problems/diameter-of-binary-tree/discuss/101132/java-solution-maxdepth

https://leetcode.com/problems/diameter-of-binary-tree/discuss/101115/543-diameter-of-binary-tree-c_recursive_with-brief-explanation

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation