124. Binary Tree Maximum Path Sum

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.

方法一:我的思路,采用后序遍历算法int maxPath(TreeNode*root,int &sum),返回值返回子树根节点到叶子节点(可能不一定到叶子节点)路径最大的值,这条路径可能只有根节点(这种情况左右子树最大路径值都为复制)。sum变量保存节点的最大路径值

/**

 *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  sum=INT_MIN;

       maxPath(root,sum);

       return sum;

    }

   int maxPath(TreeNode* root,int &sum)//返回值该保存什么值?应该保存二叉树路径和的最大值。

    {

       if(root==NULL)

       {

           return 0;

       }

       int left=maxPath(root->left,sum);

       int right=maxPath(root->right,sum);

      int sum1=max(left+right,max(left,right))+root->val;

      // int sum2=max(sum1,root->val);//有可能根节点很大,

       sum=max(sum, max(sum1,root->val));

        return max(root->val,(max(left,right)+root->val));

    }

};

方法二:19ms优化版本(leedcode大神级的方案),将最大路径为负值的值置为,0,当根节点的左子树和右子树的最大路径值都为负值时,此时根节点的最大路径值即为根节点的值,若左子树和右子树有一个不为零,则根节点的最大路径为根节点的值加上左子树和右子树中最大路径不为零的那一颗子树的最大路径值。可以避免比较大小

体会一下如何优化的。if(l<0) l=0;可以避免比较大小。

class Solution {

public:

   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;}

        return root->val + max(l,r);

    }

   

   int maxPathSum(TreeNode* root) {

       int max = INT_MIN;

       maxToRoot(root,max);

       return max;

    }

};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值