Cover image for LeetCode Hot 100 P543 Diameter of Binary Tree

LeetCode Hot 100 P543 Diameter of Binary Tree


Timeline

Timeline

2026-03-14

init

Post-order traversal, depth of binary tree

Problem:

Iterative approach:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode()
: val(0)
, left(nullptr)
, right(nullptr)
{
}
TreeNode(int x)
: val(x)
, left(nullptr)
, right(nullptr)
{
}
TreeNode(int x, TreeNode *left, TreeNode *right)
: val(x)
, left(left)
, right(right)
{
}
};

#include <stack>
#include <unordered_map>

using std::stack;
using std::unordered_map;

class Solution {
public:
int diameterOfBinaryTree(TreeNode *root)
{
// Maximum of left subtree depth + right subtree depth for each node
stack<TreeNode *> stk;
unordered_map<TreeNode *, int> node_depth;
TreeNode *last = nullptr, *p = root;
int res = 0, left_depth, right_depth;

while (p || !stk.empty()) {
if (p) {
stk.push(p);
p = p->left;
} else {
p = stk.top();
if (p->right && last != p->right) {
p = p->right;
} else {
// visit p

left_depth = (p->left) ? node_depth[p->left] : 0;

right_depth = (p->right) ? node_depth[p->right] : 0;

node_depth[p] = std::max(left_depth, right_depth) + 1;

res = std::max(res, left_depth + right_depth);

stk.pop();

last = p;
p = nullptr;
}
}
}

return res;
}
};

Recursive approach: essentially find the maximum sum of left and right subtree depths for each node

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
int ans;
int depth(TreeNode *rt)
{
if (rt == NULL) {
return 0; // Reached null node, return 0
}
int L = depth(rt->left); // Depth of subtree rooted at left child
int R = depth(rt->right); // Depth of subtree rooted at right child
ans = max(ans, L + R + 1); // Calculate d_node = L + R + 1 and update ans
return max(L, R) + 1; // Return depth of subtree rooted at this node
}

public:
int diameterOfBinaryTree(TreeNode *root)
{
ans = 1;
depth(root);
return ans - 1;
}
};