时间轴

2026-03-14

init


题目:

非递归写法:

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)
{
// 每个节点左子树深度+右子树深度得最大值
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;
}
};

递归写法:实际上是求每个节点的左子树和右子树深度之和的最大值

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; // 访问到空节点了,返回0
}
int L = depth(rt->left); // 左儿子为根的子树的深度
int R = depth(rt->right); // 右儿子为根的子树的深度
ans = max(ans, L + R + 1); // 计算d_node即L+R+1 并更新ans
return max(L, R) + 1; // 返回该节点为根的子树的深度
}

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