LeetCode-543-二叉树的直径

思路
计算左右最大深度和
代码
class Solution {
int m=0;
public int diameterOfBinaryTree(TreeNode root){
dfs(root);
return m;
}
public int dfs(TreeNode root){
if(root==null) return 0;
int l=dfs(root.left);
int r=dfs(root.right);
m=Math.max(m,l+r);
return Math.max(l,r)+1;
}
}
这篇博客介绍了如何解决LeetCode上的第543题——二叉树的直径。作者通过深度优先搜索(DFS)策略,分别计算左子树和右子树的最大深度,并在过程中更新全局的最大直径。最后返回树的最大直径。
309

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



