Binary Tree Maximum Path Sum
2013-11-23 13:38
323 查看
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
思路:
递归调用函数。用函数comput计算从子树到根节点传递到根节点的父节点的值,然后用一个result记录在递归过程中求得的最大值。
代码:
The path may start and end at any node in the tree.
For example:
Given the below binary tree,
1 / \ 2 3
Return
6.
思路:
递归调用函数。用函数comput计算从子树到根节点传递到根节点的父节点的值,然后用一个result记录在递归过程中求得的最大值。
代码:
int max(int a, int b){ if(a > b) return a; return b; } int comput(TreeNode *root, int &result){ if(root == NULL) return 0; int left = comput(root->left, result); int right = comput(root->right, result); int arch = left + right + root->val; int valToParent = max(root->val, root->val+max(left, right)); result = max(result, max(arch, valToParent)); return valToParent; } int maxPathSum(TreeNode *root) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. int result = INT_MIN; comput(root, result); return result; }
相关文章推荐
- Leetcoe Binary Tree Maximum Path Sum
- LeetCode124 Binary Tree Maximum Path Sum
- LeetCode: Binary Tree Maximum Path Sum 解题报告
- Binary Tree Maximum Path Sum leetcode
- DFS Binary Tree Maximum Path Sum
- [LeetCode] Binary Tree Maximum Path Sum(最大路径和)
- Binary Tree Maximum Path Sum
- Leetcode#124 Binary Tree Maximum Path Sum
- 【LeetCode】Binary Tree Maximum Path Sum 解题报告
- 【LeetCode】Binary Tree Maximum Path Sum
- 124. Binary Tree Maximum Path Sum
- leetcode--BinaryTreeMaximumPathSum
- 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
- leetcode - Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- *LeetCode-Binary Tree Maximum Path Sum