【leetcode】binary-tree-maximum-path-sum
来源:互联网 发布:淘宝怎么收藏宝贝截图? 编辑:程序博客网 时间:2024/05/21 09:18
后序遍历;注意两个值,1.以该节点为最高节点的路径上所有节点的和;2.通过该节点(或者一直向下)孩子路径的最大值;
前者不需要保存,只是为了求解,每次跟最大值比较保留较大值即可,后者为了便于计算上层节点的为最高父节点的和,需要暂时保存;
开始时想错了,浪费了很长时间;后来想要保存上述两个值,但需要修改TreeNode,看过discussion上别人的代码,才写出来;
代码如下:
//2014年8月21日15:16:05//2014年8月21日16:44:48#include <iostream>using namespace std;struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {}};class Solution {public: int maxValue = 0; int maxPathSum(TreeNode *root) { maxValue = root->val; GetMaxChildValue(root); return maxValue; } int GetMaxChildValue(TreeNode *root) { int ret = 0; int leftChildValue = 0,rightChildValue = 0; if(root->left != NULL){ leftChildValue = GetMaxChildValue(root->left); } if(root->right != NULL){ rightChildValue = GetMaxChildValue(root->right); } int maxValue1 = max(maxValue,leftChildValue+rightChildValue+root->val); int maxValue2 = max(leftChildValue+root->val,rightChildValue+root->val); maxValue = max(maxValue1,maxValue2); ret = max(max(root->val,root->val+leftChildValue),root->val+rightChildValue); return ret; }};int main(){ struct TreeNode A(1); struct TreeNode B(-2); struct TreeNode C(3); A.left = &B; A.right = &C; Solution S; cout << S.maxPathSum(&A) << endl; return 0;}
0 0
- *****(leetcode) Binary Tree Maximum Path Sum (tree)
- LeetCode Binary Tree Maximum Path Sum
- [Leetcode] Binary Tree Maximum Path Sum
- [leetcode] Binary Tree Maximum Path Sum
- LeetCode Binary Tree Maximum Path Sum
- [LeetCode] Binary Tree Maximum Path Sum
- leetcode Binary Tree Maximum Path Sum
- 【leetcode】Binary Tree Maximum Path Sum
- LeetCode - Binary Tree Maximum Path Sum
- [LeetCode]Binary Tree Maximum Path Sum
- [Leetcode]Binary Tree Maximum Path Sum
- Leetcode: Binary Tree Maximum Path Sum
- LeetCode-Binary Tree Maximum Path Sum
- [leetcode] Binary Tree Maximum Path Sum
- LeetCode - Binary Tree Maximum Path Sum
- LeetCode 124: Binary Tree Maximum Path Sum
- 【Leetcode】Binary Tree Maximum Path Sum
- LeetCode | Binary Tree Maximum Path Sum
- 获取游戏笔记本电脑的终极游戏体验
- 获取有关的iOS 7越狱更多的信息
- 经济实惠的ERP软件系统的小型和中型商业公司
- 管理文件审查的基础
- 管理DistributionLogistics - 进出口ERP解决方案
- 【leetcode】binary-tree-maximum-path-sum
- 简指南越狱的iOS及原因,负责其
- get 与 post 的区别
- 简单的步骤,以与Android应用金钱
- 简单的方法Android的数据恢复你的Android手机
- 减肥食疗佳品——柚子
- 简化程序迅速ERP软件
- 每个人都不知道自己的长处吗?
- 盒子的2D引擎创建平台2D安卓游戏