【LeetCode】81. Binary Tree Maximum Path Sum

题目描述(Hard)

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.

题目链接

https://leetcode.com/problems/path-sum/description/

Example 1:

Input: [1,2,3]

       1
      / \
     2   3

Output: 6

Example 2:

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

扫描二维码关注公众号,回复: 3741754 查看本文章

   -10
   / \
  9  20
    /  \
   15   7

Output: 42

算法分析

类似【剑指】42.连续子数组的最大和,对于有两个方向的二叉树,先算出左右子树的结果L和R,如果L>0,那么对于后续结果是有利的,我们加上L,R同理。最后返回值应只返回一个方向上的值,因为递归只能向父节点返回。

如Example2中所示,路径为15->20->7。

提交代码:

class Solution {
public:
    int maxPathSum(TreeNode* root) {
        int max_sum = INT_MIN;
        dfs(root, max_sum);
        return max_sum;
    }
    
    int dfs(TreeNode* root, int& max_sum) {
        if (!root) return 0;
        
        int left = dfs(root->left, max_sum);
        int right = dfs(root->right, max_sum);
        
        int curr = root->val;
        if (left > 0) curr += left;
        if (right > 0) curr += right;
        
        max_sum = max(max_sum, curr);
        
        return max(left, right) > 0 ? max(left, right) + root->val : root->val;
    }
};

猜你喜欢

转载自blog.csdn.net/ansizhong9191/article/details/82881579