天天看点

LeetCode 124.Binary Tree Maximum Path Sum (二叉树中的最大路径和)

题目描述:

给定一个非空二叉树,返回其最大路径和。

本题中,路径被定义为一条从树中任意节点出发,达到任意节点的序列。该路径至少包含一个节点,且不一定经过根节点。

示例 1:

输入: [1,2,3]

       1
      / \
     2   3

输出: 6
      

示例 2:

输入: [-10,9,20,null,null,15,7]

   -10
   / \
  9  20
    /  \
   15   7

输出: 42      

AC C++ Solution:

解题思路:自下而上更新树的每个节点,返回子树的最大路径和,同时更新max值。

代码:

class Solution {
public:
    int maxPathSum(TreeNode* root) {
        int max = INT_MIN;
        maxToRoot(root,max);
        return max;
    }
    
private:
    int maxToRoot(TreeNode *root, int &re) {
        if(!root)   return 0;
        int l = maxToRoot(root->left,re);
        int r = maxToRoot(root->right,re);
        if(l < 0)   l = 0;
        if(r < 0)   r = 0;
        if(l+r+root->val > re)  re = l + r + root->val; //遍历更新max值
        return root->val + max(l,r);                    //向父节点返回子树的最大路径和
    }
};