模板
后序遍历
public int dfs(TreeNode root) {
if (null == root) {
return 0;
}
// 获取左边最大
int left = dfs(root.left);
// 获取右边最大
int right = dfs(root.right);
// 和临时变量比较
res = Math.max(Math.max(0, left) + Math.max(0, right) + root.val, res);
// 返回左边、右边或自己三个节点最大一个
return root.val + Math.max(0, Math.max(left, right));
}
解答
public class Solution {
int res = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
if (null == root) {
return 0;
}
dfs(root);
return res;
}
public int dfs(TreeNode root) {
if (null == root) {
return 0;
}
int left = dfs(root.left);
int right = dfs(root.right);
res = Math.max(Math.max(0, left) + Math.max(0, right) + root.val, res);
return root.val + Math.max(0, Math.max(left, right));
}
}