leetcode:Binary Tree Maximum Path Sum
来源:互联网 发布:京东java面试经验 编辑:程序博客网 时间:2024/06/06 10:07
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,
1 / \ 2 3
Return 6
.
思路:以某结点n为路径中的起始结点求此路径的最大值,此路径的最大值 = n->val + ( max(左树最大路径值,右树路径最大值) > 0 ?max(左树最大路径值,右树路径最大值) : 0 )。如果左右树都小于0,那就不要累计了加0就可以,否则加上左右路径中最大的那个。。
但是n的结点值可能为负数:当max(左树最大路径值,右树路径最大值) + n->val >0 时,以n结点为路径还是有用的,说不定和n结点的父节点串起来就会有更大的路径。但不一定会出现更大路径。所以每层递归的时候都要记录目前的最大路径值ret:
int sum=root->val; // 以root为开始结点的路径最大值
if(leftValue>0)
sum+=leftValue;
if(rightValue>0)
sum+=rightValue;
ret=max(sum,ret);//root->val为负数没关系,因为在求leftValue和rightValue的时候先运行了这一步赋值设置过ret,对ret的结果没影响
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: //返回以root为结点的路径的最大值 int dfs(TreeNode* root,int &ret){ if(root==NULL) return 0; int leftValue=dfs(root->left,ret); int rightValue=dfs(root->right,ret); int sum=root->val; if(leftValue>0) sum+=leftValue; if(rightValue>0) sum+=rightValue; ret=max(sum,ret);//此时路径值大 就先存储目前最大的临时路径值---也许它就是最大的了,也许其他递归返回还会更新,但不管他先存了!! //一定要有root结点,root为负数也没事,因为上一步已经记录目前的最大值了。说不定以root为结点串起来的路径的值更大,即使root的值为负数,因为root它还有左右路径 //且路径只能在left和right中选择大于0的一条!!! return root->val + (max(leftValue,rightValue)>0?max(leftValue,rightValue):0); } int maxPathSum(TreeNode* root) { int ret=INT_MIN; dfs(root,ret); return ret; }};
- *****(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
- Swift(十七、可选链)
- Android应用中平滑的手写效果实现
- Plist 数据库的使用方法
- 新浪微博SDK抛出异常-[__NSDictionaryM weibosdk_WBSDKJSONString]: unrecognized selector sent to instance 0x7fb
- NYOJ 202 红黑树 【二叉树 中序遍历】
- leetcode:Binary Tree Maximum Path Sum
- android-Ultra-Pull-To-Refresh源码分析
- POJ 2777 Count Color 【线段树 区间更新 按位或运算】
- V字形研发模式中的测试
- 基于Objective-C OC的省市区代码(建立省市区类 与数组)
- 滤波方法 PF KF EKF UKF
- 0019将字符串逆序操作
- 句柄的理解
- Eclipse常用快捷键