0
点赞
收藏
分享

微信扫一扫

【学透二叉树-二叉树中的最大路径和】

题目描述:
在这里插入图片描述
代码实现:

class Solution {
	//最大路径和
    private int res = Integer.MIN_VALUE;
    public int maxPathSum(TreeNode root) {
        /**
        对于任意一个节点, 如果最大路径和包含该节点, 那么只可能是两种情况:
        1. 其左右子树中所构成的路径较大的那个加上该节点的值后向父节点回溯构成最大路径
        2. 左右子树都在最大路径中, 加上该节点的值构成了最终的最大路径
        **/
        getMax(root);
        return res;
    }
    private int getMax(TreeNode root) {
        if(root == null){
			return 0;
		} 
        int left = Math.max(0, getMax(root.left)); // 如果子树路径和为负,则应当置0表示最大路径不包含子树
        int right = Math.max(0, getMax(root.right));
        res = Math.max(res, root.val + left + right); // 判断该节点包含左右子树的路径和是否大于当前最大路径和
        return Math.max(left, right) + root.val;
    }
}
举报

相关推荐

0 条评论