Binary Tree Maximum Path Sum Leetcod c++

I use the iterate function to solve this problem.

when the rood have a left child or a right child, we just call the function to calculate the max value of the subtree.

But we must pay attention to the return value. It is not the current max value. It is the biggest value of root and left child path, root and right child path , root itself(because both the left child and the right child might be negative)

the whole code is attached.

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
 //I did not understand the question clearly, this is a distanse problem in random two nodes
 //thus, we can use the iterate method to sove this problem and we should pay attention to the 
 //return value.
class Solution {
public:
int max_num = -10000;
int maxPathSum2(TreeNode *root)
{
    
    int templeft = 0;
    int tempright = 0;
	int value = root->val;
	int value2 = value;
	if(value>max_num)
	    max_num = value;
	if(root->left == NULL && root->right == NULL)
		return value;
	if(root->left!=NULL)
	{
		templeft = maxPathSum2(root->left);
		if(templeft >0)
			value += templeft;
    }
    if(root->right!=NULL)
    {
    	tempright = maxPathSum2(root->right);
    	if(tempright > 0)
    		value += tempright;
    }
    if(value > max_num) max_num = value;
    int ret = 0;
    ret = max(value2,max(value2 + templeft,value2 + tempright));//here as we know, the leftchild and the rightchild are both probably be negative, so ret is the value of three options, the right child and the right child and the root it self.
    return ret;
}
    
int maxPathSum(TreeNode *root) {
    if(root == NULL)
    	return 0;
    maxPathSum2(root);
    return max_num;
    }
};

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值