写出来了但是耗时很长,应该考虑怎么剪枝
也不是,感觉自己把该递归判断的地方写错了
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int max = 0;
public int diameterOfBinaryTree(TreeNode root) {
if(root==null) return 0;
dfs(root);
return max;
}
int dfs(TreeNode root){
if(root==null) return 0;
int a = dfs(root.left);
int b = dfs(root.right);
max = Math.max(max,a+b);
return Math.max(a,b)+1;
}
}
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int diameterOfBinaryTree(TreeNode root) {
if(root==null) return 0;
int a = dfs(root.left,0);
int b = dfs(root.right,0);
//System.out.println(a + " " + b);
return Math.max(Math.max(diameterOfBinaryTree(root.left),diameterOfBinaryTree(root.right)),a+b);
}
int dfs(TreeNode root, int depth){
if(root==null) return depth;
depth++;
return Math.max(dfs(root.left,depth),dfs(root.right,depth));
}
}

这篇博客探讨了如何优化计算二叉树直径的算法。作者通过两个不同的实现,展示了如何使用深度优先搜索(DFS)来遍历树,并在过程中记录最大路径长度。第一个实现中,存在耗时过长的问题,作者认为可能在递归判断部分存在错误。第二个实现则引入了深度参数,通过存储路径深度来减少重复计算,从而提高效率。博客着重于算法的剪枝策略和效率改进。

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



