LeetCode 124:Binary Tree Maximum Path Sum
2015-12-30 22:36
381 查看
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,
Return
Subscribe to see which companies asked this question
![](http://img.blog.csdn.net/20151230223439926?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
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.
Subscribe to see which companies asked this question
//找出二叉树任意一点到另一点的路径,使得和最大. //解题思路:后序遍历,先计算左右子树的值l和r,若l<0或r<0,则不用加上 class Solution { public: int maxSum; int maxPathSum(TreeNode* root) { if (root == NULL) return 0; maxSum =root->val; dfs(root); return maxSum; } int dfs(TreeNode* root){ if (root == NULL) return 0; int l = dfs(root->left); int r = dfs(root->right); int sum = root->val; if (l > 0) sum = sum + l; if (r > 0) sum = sum + r; maxSum = max(maxSum, sum); return max(root->val, max(l + root->val, r + root->val)); } };
#include<iostream>
#include<new>
#include<vector>
#include<algorithm>
using namespace std;
//Definition for binary tree
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
//找出二叉树任意一点到另一点的路径,使得和最大. //解题思路:后序遍历,先计算左右子树的值l和r,若l<0或r<0,则不用加上 class Solution { public: int maxSum; int maxPathSum(TreeNode* root) { if (root == NULL) return 0; maxSum =root->val; dfs(root); return maxSum; } int dfs(TreeNode* root){ if (root == NULL) return 0; int l = dfs(root->left); int r = dfs(root->right); int sum = root->val; if (l > 0) sum = sum + l; if (r > 0) sum = sum + r; maxSum = max(maxSum, sum); return max(root->val, max(l + root->val, r + root->val)); } };
void createTree(TreeNode *&root)
{
int i;
cin >> i;
if (i != 0)
{
root = new TreeNode(i);
if (root == NULL)
return;
createTree(root->left);
createTree(root->right);
}
}
int main()
{
Solution s;
TreeNode *root;
createTree(root);
int sum = s.maxPathSum(root);
cout << sum << endl;
system("pause");
return 0;
}
相关文章推荐
- java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
- 请求网络下载图片2(读取是否存在缓存图片)
- 正则表达式匹配括号中的字符,不包括括号
- JPG文件格式
- RS422接线方法
- java Pattern和Matcher详解
- Linux Nginx配置nginx.conf效率很高
- 【数据结构+算法】【(线性)动态规划】--- 求最长回文串的长度
- 软件测试
- 抽象工厂模式
- eclipse里面设置JVM参数的问题
- 用python爬虫抓站的一些技巧总结
- 一篇阅读理解的分析Until the twentieth century cigarettes were not an important threat to public health
- 实现ListView图文混排 —— 获取Json数据
- java 文件处理总结
- 欢迎使用CSDN-markdown编辑器
- 大数据点滴
- 12.30总结
- 密钥仓库(证书导入keystore)
- 隐马尔可夫模型的前向算法(java实现),今天奉上