Diameter of Binary Tree

DFS returns subtree depth; meanwhile track best left + right pair at any bend.

Easy
Time O(n) Space O(h)
LeetCode
3 min read
tree dfs

Problem#

Return the length (in edges) of the longest path between any two nodes in a binary tree.

Examples#

  • [1,2,3,4,5]3 (4-2-1-3 or 5-2-1-3)
  • [1,2]1

Constraints#

  • The number of nodes is in [1, 10^4].

Approach#

DFS each node returns its subtree depth. At each node, the candidate diameter through it is leftDepth + rightDepth. Track the global max.

Solution#

Diameter of Binary Tree
class Solution {
public:
int diameterOfBinaryTree(TreeNode* root) {
int best = 0;
function<int(TreeNode*)> dfs = [&](TreeNode* u) -> int {
if (!u) return 0;
int l = dfs(u->left);
int r = dfs(u->right);
best = max(best, l + r);
return 1 + max(l, r);
};
dfs(root);
return best;
}
};

Editorial#

Same shape as Binary Tree Maximum Path Sum — return the extendable arm depth, track the bend separately. Depth-in-edges differs from depth-in-nodes by one; the formula uses 1 + max(l, r) for “depth as 1 plus deeper child”.

Complexity#

  • Time: O(n).
  • Space: O(h).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.