Day 2.1
二叉树中的最大路径和
题目
思路
定义方法lmax
找到从root
向左走所能得到的最大和,方法rmax
找到从root
向右走所能得到的最大和,再遍历每个节点作为root
计算max
class Solution {
int max = -1000;
public int maxPathSum(TreeNode root) {
getAns(root);
return max;
}
//遍历每个节点,计算节点值与该节点的lmax与rmax之和,max保存所有节点中结果的最大值
private void getAns(TreeNode node) {
if (node == null) return;
if(lmax(node)+rmax(node)-node.val>max) max = lmax(node)+rmax(node)-node.val;
getAns(node.left);
getAns(node.right);
}
//从root向左走所能得到的最大和
public int lmax(TreeNode root){
if(root==null)return 0;
return Math.max(root.val,(root.val+Math.max(lmax(root.left),rmax(root.left))));
}
//从root向右走所能得到的最大和
public int rmax(TreeNode root){
if(root==null)return 0;
return Math.max(root.val,(root.val+Math.max(lmax(root.right),rmax(root.right))));
}
}
参考答案后,发现可以把getAns
, lmax
, rmax
三个方法合并以减少递归次数,优化运行时间
class Solution {
int res = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
if (root == null) return 0;
dfs(root);
return res;
}
public int dfs(TreeNode root) {
if (root == null) return 0;
int leftMax = Math.max(0, dfs(root.left)); // 左孩子贡献
int rightMax = Math.max(0, dfs(root.right)); // 右孩子贡献
res = Math.max(res, root.val + leftMax + rightMax); // 更新res
return root.val + Math.max(leftMax, rightMax); // 返回当前节点的总贡献
}
}