leetcode 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 does not need to go through the root.

For example:
Given the below binary tree,

       1
      / \
     2   3

Return 6.

此题题意是:求二叉树中的一条和为最大的路径之和,该路径由有连接的节点组成,并不一定要root节点在路径中。

该路径有个特点,肯定是一个节点为最高层节点,路径的左段为该节点左孩子往下延伸的一条路径,右段为该节点右孩子往下延伸的一条路径。

采用递归的方法,先序处理二叉树,每访问到一个节点就计算以该节点为最高层节点往左右延伸的路径和,并在每次递归记录最大和。

代码如下:

class Solution {
private:
    int maxval;
public:
    int maxPathSum(TreeNode* root) {
    	if(root == NULL)
    		return 0;
    	maxval = INT_MIN;
    	maxsum(root);
    	return maxval;
    }
    int maxsum(TreeNode* root)
    {
    	if(root == NULL)
    		return 0;
    	int val = root->val;
    	int left, right;
    	left = maxsum(root->left);//返回的是左孩子为最高节点的一条从上到下的路径
    	if(left>0)
    		val += left;
    	right = maxsum(root->right);//返回的是右孩子为最高节点的一条从上到下的路径
    	if(right>0)
    		val += right;
    	if(val > maxval)//每次递归都计算以该层计算节点为最高层节点的路径!!!
    		maxval = val;
    	return max(root->val, max(root->val+left, root->val+right));//注意此返回值,是返回当前值、当前值加左孩子路径值或加右孩子路径值!!!
    }
};



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值