博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode: Binary Tree Maximum Path Sum
阅读量:4360 次
发布时间:2019-06-07

本文共 618 字,大约阅读时间需要 2 分钟。

思路:

1. 对于每一个节点, 返回其所在子树所能提供的最大值, 且该最大值必须是单支的, WA 过

2. max(0, max(lf, rt))+root->val, 可以仅返回根节点, WA 过

3. 需要维护一个全局最优解 ans, WA 过

代码:

class Solution {public:	int ans;	int solve_dp(TreeNode *root) {		if(root == NULL)			return 0;		int sum = root->val;		int lf = 0, rt = 0;		if(root->left)		lf = solve_dp(root->left);				if(root->right) 		rt = solve_dp(root->right);		if(lf > 0)			sum += lf;		if(rt > 0)			sum += rt;		ans = max(ans, sum);		return max(0, max(lf, rt))+root->val;	}    int maxPathSum(TreeNode *root) {		ans = -100000000;		solve_dp(root);		return ans;    }};

  

转载于:https://www.cnblogs.com/xinsheng/p/3459277.html

你可能感兴趣的文章
Entity Framework的查询
查看>>
ZH奶酪:Python按行读取文件
查看>>
07-使用循环进行遍历数组(运算符)
查看>>
控件布局通用解决方案
查看>>
scala流程控制语句以及方法和函数
查看>>
MySQL的sql_mode模式
查看>>
windows命令——explorer
查看>>
<转载>Bootstrap 入门教程 http://www.cnblogs.com/ventlam/archive/2012/05/28/2520703.html 系列...
查看>>
jquery和js cookie的使用解析
查看>>
类的内置方法
查看>>
世界是数字的 读后感
查看>>
算法项目步骤流程
查看>>
POJ 2942 Knights of the Round Table ★(点双连通分量+二分图判定)
查看>>
10.scheam.xml的配置
查看>>
Android Studio 生成aar包多Module引用问题
查看>>
hdu--1540 Tunnel Warfare(线段树+区间合并)
查看>>
通过命令给Linux(CentOS)分区
查看>>
Sprint1规划暨first stand up meeting
查看>>
python接口自动化3-自动发帖(session)
查看>>
复杂问题的简单抽象:魔兽世界中的兔子们
查看>>