class Solution {
int res = 0;
public int diameterOfBinaryTree(TreeNode root) {
if(root == null)
return 0;
depth(root);
return res;
}
public int depth(TreeNode root){
if(root == null)
return 0;
int left = depth(root.left);
int right = depth(root.right);
res = Math.max(res,left+right);
return Math.max(left, right) + 1;
}
}
递归的两个return:一个是终止条件,一个是返回上一级的条件。
然后设置一个全局判断值。
从叶子结点开始向上,每个子节点的最长左右长度和可以与已有的最长值进行判断,判断完成后向子节点的父节点走的时候自动携带该子节点上最长的一条路径值,不能通过子节点转弯的那种。