编程练习(第五周)

124. Binary Tree Maximum Path Sum

  • Total Accepted: 90097
  • Total Submissions: 354576
  • Difficulty: Hard
  • Contributors: Admin

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 Path(TreeNode* root,int&maxSum)
    {
        if(root==NULL)
            return 0;
        int leftmax = Path(root->left,maxSum);
        int rightmax = Path(root->right,maxSum);
        maxSum = max(maxSum,max(0,leftmax)+max(0,rightmax)+root->val);
        return max(0,max(leftmax,rightmax))+root->val;
    }
    int maxPathSum(TreeNode *root) {
        int maxSum = INT_MIN;
        Path(root,maxSum);
        return maxSum;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值