leetcode Binary Tree Maximum Path Sum
2016-09-09 09:46
302 查看
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
此题题意是:求二叉树中的一条和为最大的路径之和,该路径由有连接的节点组成,并不一定要root节点在路径中。
该路径有个特点,肯定是一个节点为最高层节点,路径的左段为该节点左孩子往下延伸的一条路径,右段为该节点右孩子往下延伸的一条路径。
采用递归的方法,先序处理二叉树,每访问到一个节点就计算以该节点为最高层节点往左右延伸的路径和,并在每次递归记录最大和。
代码如下:
class Solution {
private:
int maxval;
public:
int maxPathSum(TreeNode* root) {
if(root == NULL)
return 0;
maxval = INT_MIN;
maxsum(root);
return maxval;
}
int maxsum(TreeNode* root)
{
if(root == NULL)
return 0;
int val = root->val;
int left, right;
left = maxsum(root->left);//返回的是左孩子为最高节点的一条从上到下的路径
if(left>0)
val += left;
right = maxsum(root->right);//返回的是右孩子为最高节点的一条从上到下的路径
if(right>0)
val += right;
if(val > maxval)//每次递归都计算以该层计算节点为最高层节点的路径!!!
maxval = val;
return max(root->val, max(root->val+left, root->val+right));//注意此返回值,是返回当前值、当前值加左孩子路径值或加右孩子路径值!!!
}
};
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.
此题题意是:求二叉树中的一条和为最大的路径之和,该路径由有连接的节点组成,并不一定要root节点在路径中。
该路径有个特点,肯定是一个节点为最高层节点,路径的左段为该节点左孩子往下延伸的一条路径,右段为该节点右孩子往下延伸的一条路径。
采用递归的方法,先序处理二叉树,每访问到一个节点就计算以该节点为最高层节点往左右延伸的路径和,并在每次递归记录最大和。
代码如下:
class Solution {
private:
int maxval;
public:
int maxPathSum(TreeNode* root) {
if(root == NULL)
return 0;
maxval = INT_MIN;
maxsum(root);
return maxval;
}
int maxsum(TreeNode* root)
{
if(root == NULL)
return 0;
int val = root->val;
int left, right;
left = maxsum(root->left);//返回的是左孩子为最高节点的一条从上到下的路径
if(left>0)
val += left;
right = maxsum(root->right);//返回的是右孩子为最高节点的一条从上到下的路径
if(right>0)
val += right;
if(val > maxval)//每次递归都计算以该层计算节点为最高层节点的路径!!!
maxval = val;
return max(root->val, max(root->val+left, root->val+right));//注意此返回值,是返回当前值、当前值加左孩子路径值或加右孩子路径值!!!
}
};
相关文章推荐
- [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
- Binary Tree Maximum Path Sum -- LeetCode
- 【LeetCode】Binary Tree Maximum Path Sum 解题报告
- leetcode Binary Tree Maximum Path Sum
- LeetCode: Binary Tree Maximum Path Sum [124]
- 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
- [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
- Binary Tree Maximum Path Sum [leetcode] dp