leetcode_c++:树:Binary Tree Maximum Path Sum(124)
2016-08-26 15:37
465 查看
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,
return 6
直接 DFS 就可以了,返回以这一棵子树且一端在上的最大路径,然后维护一个最大路径就行了。
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
算法
求一棵二叉树上的最大路径。直接 DFS 就可以了,返回以这一棵子树且一端在上的最大路径,然后维护一个最大路径就行了。
class Solution { private: int ret; int dfs(TreeNode *root) { if (root == NULL) return 0; int left_sum = max(0, dfs(root->left)); int right_sum = max(0, dfs(root->right)); ret = max(ret, left_sum + right_sum + root->val); return max(left_sum, right_sum) + root->val; } public: int maxPathSum(TreeNode *root) { ret = INT_MIN; dfs(root); return ret; } };
相关文章推荐
- [leetcode-124]Binary Tree Maximum Path Sum(c++)
- [LeetCode 124] Binary Tree Maximum Path Sum
- LeetCode: Binary Tree Maximum Path Sum [124]
- leetcode 124 —— Binary Tree Maximum Path Sum
- 124 Binary Tree Maximum Path Sum [Leetcode]
- LeetCode124—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, Hard] Binary Tree Maximum Path Sum
- *Leetcode_binary-tree-maximum-path-sum (updated c++ and python version)
- LeetCode 124 Binary Tree Maximum Path Sum
- [LeetCode]题解(python):124-Binary Tree Maximum Path Sum
- LeetCode124: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(Java)
- Java for LeetCode 124 Binary Tree Maximum Path Sum
- LeetCode 124:Binary Tree Maximum Path Sum