思想: 以root为根节点的树其最大路径长度 = 左子树深度+右子树深度 ,所以套求深度的模板,然后添加一句更新当前root的最长路径的代码即可
时间复杂度O(n)
class Solution {
int res;
public int helper(TreeNode root){
if(root==null)return 0;
if(root.left==null&&root.right==null)return 1;
int leftDepth = helper(root.left);
int rightDepth = helper(root.right);
res = Math.max(res,(leftDepth+rightDepth));
return Math.max(leftDepth,rightDepth)+1;
}
public int diameterOfBinaryTree(TreeNode root) {
if(root==null||root.left==null&&root.right==null)return 0;
helper(root);
return res;
}
}