Binary Tree Maximum Path Sum
2013-04-01 23:18
281 查看
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,
Return
其实这个题目不难,但是我折腾了好久。
我第一次做这个题目的用了很直观的方法,对于每一个节点求取通过它的maxmum path sum,方法是用递归求深度,然后 left + root-> val + right
然后再遍历所有的节点,找到global maximum
这样做会很很多重复的计算导致大集合没过
但其实呢,在用递归求深度的时候就可以顺便把最终的结果求出来了,方法是设一个全局变量。
136ms过大集合~
The path may start and end at any node in the tree.
For example:
Given the below binary tree,
1 / \ 2 3
Return
6.
其实这个题目不难,但是我折腾了好久。
我第一次做这个题目的用了很直观的方法,对于每一个节点求取通过它的maxmum path sum,方法是用递归求深度,然后 left + root-> val + right
然后再遍历所有的节点,找到global maximum
这样做会很很多重复的计算导致大集合没过
但其实呢,在用递归求深度的时候就可以顺便把最终的结果求出来了,方法是设一个全局变量。
136ms过大集合~
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { int ret; public: int depth(TreeNode *root){ if(!root) return 0; int l = max(depth(root -> left), 0); int r = max(depth(root -> right), 0); int cur = l + r + root -> val; ret = max(ret, cur); return max(l, r) + root -> val; } int maxPathSum(TreeNode *root) { // Start typing your C/C++ solution below // DO NOT write int main() function ret = INT_MIN; depth(root); return ret; } };
相关文章推荐
- [LeetCode]Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- 【树形dp】Binary Tree Maximum Path Sum
- LeetCode Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- binary-tree-maximum-path-sum Java code
- [leetcode]Binary Tree Maximum Path Sum
- LeetCode—***寻找二叉树中任意两个节点之间的最大值Binary Tree Maximum Path Sum
- LeetCode Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum (二叉树路径和的最大值) 【leetcode】
- [leetcode]Binary Tree Maximum Path Sum
- 二叉树最大路径和-Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- 124. Binary Tree Maximum Path Sum
- [LeetCode]Binary Tree Maximum Path Sum
- 124. Binary Tree Maximum Path Sum
- LeetCode_Binary Tree Maximum Path Sum
- [LeetCode] Binary Tree Maximum Path Sum
- 20150708 lintcode 总结 Binary Tree Maximum Path Sum Show result *****
- LeetCode – Refresh – Binary Tree Maximum Path Sum