[leetcode]Binary Tree Maximum Path Sum
来源:互联网 发布:jquery–1.4.2.min.js 编辑:程序博客网 时间:2024/06/05 21:50
近期为了准备笔试开始刷leetcode,记录一下希望自己可以坚持!
Binary Tree Maximum Path Sum
Given a binary tree, find the maximum path sum.
The path may start and end at any node in the tree.
For example:
Given the below binary tree,
1 / \ 2 3
Return 6
.
以上是题目
一开始我把题目理解错误,导致多次提交都是出错,经过各种搜索终于了解了这个题目的本意。(很奇怪,为什么不提供更详细的测试用例,这样也可以减少理解障碍不是 :-))
(一)题目要求分析:
1、路径最大和值包括;节点,节点+左子树,节点+右子树,其中一个,当左右子树有一个为零时,我们就舍弃这个子点,这也是我们创建递归函数的返回值。
2、当前函数包含一个变量maxSum来记录最大值,maxSum等于当前节点的,节点与左右子节点可以得到的最大值与函数返回值中大的那一个。
举例如下:
1
/ \
2 3
/ \ / \
4 -5 6 7
左子树的函数返回值为(2,4)= 6; 而此时可以得出maxSum为(1,2,4) = 7.
(二)解题技巧:
1、从根节点开始遍历访问左右子树,分别寻至叶子节点。
2、注意区分返回值与最大值的区别。
上AC代码:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */int ans;int max(int a, int b){ if(a > b) return a; else return b;}int help(struct TreeNode *root){ int ret, lsum, rsum; if(root == NULL) return 0; ret = root->val; lsum = help(root->left); rsum = help(root->right); if(lsum > 0) ret += lsum; if(rsum > 0) ret += rsum; if(ret > ans) ans = ret; return max(root->val, max(root->val + lsum, root->val + rsum));} int maxPathSum(struct TreeNode* root){ ans = root->val; help(root); return ans;}参考博客:[LeetCode 124] - 二叉树最大路径和(Binary Tree Maximum Path Sum)
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
- Java 中文乱码学习 与Spring @ResponseBody中的乱码 - Spring @ResponseBody中的乱码
- 【Java基础面试题】【01】
- ubuntu15.04中使用mkusb制作u盘启动安装ubuntu15.04
- js unicode 编码解码
- 一个100人围城一圈的算法。
- [leetcode]Binary Tree Maximum Path Sum
- Oracle基础学习登陆SQLPLUS(一)
- Phone---获取手机联系人信息
- 使用PHP QR Code生成二维码事例应用
- GRE填空词汇专项训练
- Android SQLite数据库版本升级原理解析
- iOS开发 简单实现视频音频的边下边播
- java int与integer的区别
- Javascript常用功能