Binary Tree Maximum Path Sum

Binary Tree Maximum Path Sum

  Total Accepted: 18644  Total Submissions: 92930 My Submissions

Given a binary tree, find the maximum path sum.

The path may start and end at any node in the tree.

For example:
Given the below binary tree,

       1
      / \
     2   3

Return 6.

Have you been asked this question in an interview? 

Discuss


这个是计算树的节点,从一个点到另外一个节点的路径上最大的和,算是求最优解 。

节点当中会有负数,所以不能简单的进行节点子树的最大值相加。

1.递归求解,如果这个节点的没有子树,那么这个节点的最大值就是它自己。

  在有子树的情况下,这个节点有多条路径的和可以比较,(1)左子树的最大和;(2)左子树和自己的最大和,(3)右子树的最大和,(4)右子树和自己的最大和;(5)左子树和自己和右子树的和;这四个值中最大的和总的最大值比较,并进行相应替换。返回的值只可能是(2)和(4)当中最大的

2.这样最大值就会出现。


/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
 
class Solution {
public:
    int res;
    int maxPathSum(TreeNode *root) {
            if(root==NULL)
            {
                return 0;
            }
            res = root->val;
            countSubTree(root);
            return res;
    }
    
    int countSubTree(TreeNode *sub)
    {
        int root = sub->val;
        int left =0,right = 0;
        if(sub->left!=NULL)
        {
            left = countSubTree(sub->left);
            res = res>left?res:left;
        }
        if(sub->right!=NULL)
        {
            right = countSubTree(sub->right);
            res = res>right?res:right;
        }
        int sumLeft = root+left;
        int sumRight = root+right;
		int allSum = root+left+right;
		int maxNum = max(max(sumLeft,sumRight),root);
		res = max(max(res,maxNum),allSum);
        return maxNum;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值