LeetCode 543. 二叉树的直径

543. 二叉树的直径

解题思路

后序递归计算每个节点的左右子树最大深度之和作为经过该节点的路径长度,用全局变量维护最大值,同时向上返回较大子树深度加一

参考代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
private int res = 0;
public int diameterOfBinaryTree(TreeNode root) {
solution(root);
return res;
}

private int solution(TreeNode root) {
if(root == null) {
return 0;
}
int maxLeft = solution(root.left);
int maxRight = solution(root.right);
res = Math.max(res, maxLeft + maxRight);
return Math.max(maxLeft, maxRight) + 1;
}
}

LeetCode 543. 二叉树的直径
https://sowink.cn/2026/02/08/LeetCode-543-二叉树的直径/
作者
Xurx
发布于
2026年2月8日
许可协议