124. Binary Tree Maximum Path Sum

124. Binary Tree Maximum Path Sum

Given a non-empty binary tree, find the maximum path sum.

For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.

Example 1:

Input: [1,2,3]

       1
      / \
     2   3

Output: 6

Example 2:

Input: [-10,9,20,null,null,15,7]

   -10
   / \
  9  20
    /  \
   15   7

Output: 42

方法1:

思路:

对于每个节点,计算从该节点起始的左子树右子树中的最大pathSum,strategy就是,他一直跑到每一个leaf,返回最大值。左右结果在一起计算一次和(注意deal with当前节点被算了两次),在(左,右,左+右)中选一个最大值,看能不能取代global maximum。这就是包括当前点能构成的最大pathSum。

但是这个过程中计算了众多冗余的结果,我们可以建立一个hash,来沿途记录每一个节点向下能够取到的最大pathSum,条件是必须包括它自己在内,但是没有桥梁结构,i.e. either from 左子树or 右子树。

重新思考上面的过程,站在每个节点上的时候,all i want to return back to the parent is the left max + cur, or right max + cur, not the bridge structure,因为我的父节点是不能把bridge当成自己的一部分继续使用的。这个值只用一次性计算,bridge这个值看能否取代global max之后就用不到了。那么由下向上递归的话hash也就不需要了,直接在dfs的过程中返回左右最大值+cur就可以。

Complexity

Time complexity: O(n)
Space complexity: O(h)

易错点:

  1. 何时和0 取max:左中右三个值,当左右为负的时候,是无论如何不会被包括近max path sum的,但root节点为负,可以靠连接左右来挽救。所以每次返回值需要 在left / right 当中选取较大值 + root -> val,但这个较大值要一起被0 threshold,也就是return max(0, max(left, right)) + root -> val;
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int maxPathSum(TreeNode* root) {
        int result = INT_MIN;
        maxHelper(root, result);
        return result;
    }
    
    int maxHelper(TreeNode* root, int & maxSum) {
        if (!root) return 0;
        
        int left_mx = max(maxHelper(root -> left, maxSum), 0);
        int right_mx =max(maxHelper(root -> right, maxSum), 0);
        
        maxSum = max(maxSum, left_mx + right_mx + root -> val);
        
        return max(0, max(left_mx, right_mx) + root -> val);
    }
};

二刷:

class Solution {
public:
    int maxPathSum(TreeNode* root) {
        int mx = INT_MIN;
        pathHelper(root, mx);
        return mx;
    }
    
    int pathHelper(TreeNode* root, int & mx){
        if (!root) return 0;
        int left = pathHelper(root -> left, mx);
        int right = pathHelper(root -> right, mx);
        
        mx = max(mx, max(0, left) + max(0, right) + root -> val);
        return max(0, max(left, right)) + root -> val;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值