class Solution {
int ret = 0;
public int diameterOfBinaryTree(TreeNode root) {
deepth(root);
return ret;
}
public int deepth(TreeNode root){
if(root == null) return 0;
int left_max = deepth(root.left);
int right_max = deepth(root.right);
ret = Math.max(ret, left_max+right_max);
return Math.max(left_max, right_max)+1;
}
}
class Solution {
int sum = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
if(root == null) return 0;
dfs(root);
return sum;
}
public int dfs(TreeNode root){
if(root == null) return 0;
int left = Math.max(0, dfs(root.left));
int right = Math.max(0, dfs(root.right));
sum = Math.max(sum, left+right+root.val);
return Math.max(left,right) + root.val;
}
}
这两道题都有一个共同的特点,都是通过中间的某个状态求出最终的结果,我们DFS最后返回的值都不是最终的结果。