leetcode 第124题 Binary Tree Maximum Path Sum
来源:互联网 发布:重庆时时彩杀号软件 编辑:程序博客网 时间:2024/06/06 01:29
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.
思路:用dfs遍历,先分别算出左右子树的和,若L>0,则加上L;若R>0,则加上R;最后比较root->val + max(L,R)和root->val哪个大,返回大的那个值;
C++实现:
/** * 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: int maxPathSum(TreeNode* root) { max_sum = INT_MIN; dfs(root); return max_sum; }private: int max_sum; 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 += l; if(r > 0) sum += r; max_sum = max(max_sum,sum); return max(l,r) > 0?root->val + max(l,r):root->val; }};
0 0
- leetcode 第124题 Binary Tree Maximum Path Sum
- LeetCode 124: Binary Tree Maximum Path Sum
- LeetCode 124 Binary Tree Maximum Path Sum
- LeetCode: Binary Tree Maximum Path Sum [124]
- LeetCode 124 Binary Tree Maximum Path Sum
- LeetCode(124) Binary Tree Maximum Path Sum
- [LeetCode 124]Binary Tree Maximum Path Sum
- leetcode || 124、Binary Tree Maximum Path Sum
- LeetCode #124 Binary Tree Maximum Path Sum
- leetcode 124: Binary Tree Maximum Path Sum
- 124 Binary Tree Maximum Path Sum [Leetcode]
- LeetCode 124: Binary Tree Maximum Path Sum
- LeetCode 124:Binary Tree Maximum Path Sum
- LeetCode 124 Binary Tree Maximum Path Sum
- Leetcode 124 Binary Tree Maximum Path Sum
- Leetcode #124 Binary Tree Maximum Path Sum
- Leetcode-124: Binary Tree Maximum Path Sum
- *****(leetcode) Binary Tree Maximum Path Sum (tree)
- Ajax解决聊天室问题
- HTML学习笔记一(慕课网)
- 自定义属性_TypedArray
- response对象
- 大数据:一场改变我们如何生活、工作和思考的革命(让数据说话)
- leetcode 第124题 Binary Tree Maximum Path Sum
- Java内存管理第二篇 - 内存的分配
- 《中国程序化广告技术生态图》2015年三月号更新发布
- Cassandra的timestamp类型
- swift皮筋弹动发射飞机ios源码
- 网站倒计时功能
- 关于NOLOCK的用法
- Java内存管理第三篇 - 内存可能产生的问题
- 介绍Redis