和T124,T687都是一种题
class Solution {
int max = 0;
public int diameterOfBinaryTree(TreeNode root) {
if(root == null) return 0;
dfs(root);
return max;
}
public int dfs(TreeNode root){
if(root.left == null && root.right == null) return 0;
int left = root.left == null ? 0 : dfs(root.left) + 1;
int right = root.right == null ? 0 : dfs(root.right) + 1;
max = Math.max(max, left + right);
return Math.max(left, right);
}
}~~~
本文介绍了一种求解二叉树直径的经典算法。通过深度优先搜索(DFS)递归地计算每个节点的左右子树高度,并更新最大直径。文章包含完整的Java代码实现,展示了如何有效地解决此类树形结构的问题。
679

被折叠的 条评论
为什么被折叠?



