leetcode No124. Binary Tree Maximum Path Sum

来源:互联网 发布:淘宝抢红包微信群 编辑:程序博客网 时间:2024/06/06 07:28

Question

Given a 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.

For example:
Given the below binary tree,

   1  / \ 2   3

Return 6.

Algorithm

可以用递归做,同时更新最大长度maxLength
假设左子树最长路径和(这里指的是dfs的路径)为l
假设右子树最长路径和(这里指的是dfs的路径)为r

因为负数不会增加路径和反而会减小,所以要和0比较
maxLength=max(maxLength,l+r+root->val)

Accepted Code

/** * 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) {        if(root == NULL)            return 0;        int res=INT_MIN;        helper(root,res);        return res;    }    int helper(TreeNode* root,int &res){        if(root==NULL)            return 0;        int l=max(0,helper(root->left,res));        int r=max(0,helper(root->right,res));        res=max(res,l+r+root->val);        return l>r?l+root->val:r+root->val;    }};