二叉树中的最大路径和
来源:互联网 发布:编程算法有哪些 编辑:程序博客网 时间:2024/05/18 03:23
给出一棵二叉树,寻找一条路径使其路径和最大,路径可以在任一节点中开始和结束(路径和为两个节点之间所在路径上的节点权值之和)
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/*
* @param root: The root of binary tree.
* @return: An integer
*/
int maxPathSum(TreeNode * root) {
// write your code here
if (root == NULL) {
return 0;
}
int max_sum = INT_MIN;
maxPath(root, max_sum);
return max_sum;
}
int maxPath(TreeNode * root, int& max_sum) {
int left_value = 0;
if (root->left != NULL) {
left_value = maxPath(root->left, max_sum);
}
int right_value = 0;
if (root->right != NULL) {
right_value = maxPath(root->right, max_sum);
}
// compute max sum for this nodes
int cur_sum = 0;
int cur_max = 0;
if (left_value >= 0 && right_value >= 0) {
cur_max = max(left_value, right_value) + root->val;
cur_sum = left_value + right_value + root->val;
} else if (left_value >= 0) {
cur_max = left_value + root->val;
cur_sum = cur_max;
} else if (right_value >= 0) {
cur_max = right_value + root->val;
cur_sum = cur_max;
} else {
cur_max = root->val;
cur_sum = cur_max;
}
if (cur_sum > max_sum) {
max_sum = cur_sum;
}
return cur_max;
}
};
- LintCode-二叉树中的最大路径和
- 二叉树中的最大路径和
- 二叉树中的最大路径和
- 题目:二叉树中的最大路径和
- 二叉树中的最大路径和
- 二叉树中的最大路径和
- lintcode,二叉树中的最大路径和
- 二叉树中的最大路径和
- 二叉树中的最大路径和
- 二叉树中的最大路径和-LintCode
- LintCode 二叉树中的最大路径和
- lintcode--二叉树中的最大路径和
- 二叉树中的最大路径和-LintCode
- 二叉树中的最大路径和
- 二叉树最大路径和
- 二叉树最大路径和
- 二叉树最大路径和
- lintcode-二叉树中的最大路径和-94
- 关系数据库标准语言SQL
- 最短路径—Dijkstra算法和Floyd算法
- 2018 年你需要知道的 Vue.js 组件库,完善你的应用开发
- 【代码练习8】UDP协议实现局域网屏幕广播功能
- 入学考试 -- 蓝桥杯
- 二叉树中的最大路径和
- NoteHighLight--OneNote代码高亮插件
- Struts 2中的constant配置详解
- 错误:编码GBK的不可映射字符
- linux字符设备完全分析(一)
- 51nod 1338 找格子 费用流
- Linux virtualbox 开机进不去图形化界面,停留在文本界面解决方法
- 2017-12-21php学习基础巩固第三天
- 数组去重