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
.
给定一棵二叉树,找出其中路径和最大的路径,然会返回最大路径和。
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int maxPath(int& maxSum, TreeNode *root){ if(root==NULL)return 0; //计算来自左子树的最大路径和 int maxLeft=maxPath(maxSum, root->left); //计算来自右子树的最大路径和 int maxRight=maxPath(maxSum, root->right); //计算以当前节点为转折的最大路径和 int curMaxSum=root->val; if(maxLeft>0)curMaxSum+=maxLeft; //如果从左右孩子过来的最大和是负值,则连接到当前节点,负值会使合并后的路径和更小,因此只在路径和为正的时候再连接到当前节点,具体表现为路径和相加。 if(maxRight>0)curMaxSum+=maxRight; //更新结果 if(curMaxSum>maxSum)maxSum=curMaxSum; //同样需要考虑maxLeft和maxRight的正负 int largerSum = max(maxLeft, maxRight); if(largerSum>0)return root->val+largerSum; else return root->val; } int maxPathSum(TreeNode *root) { if(root==NULL)return 0; int max=INT_MIN; maxPath(max, root); return max; } };
LeetCode: Binary Tree Maximum Path Sum [124],布布扣,bubuko.com
LeetCode: Binary Tree Maximum Path Sum [124]
原文地址:http://blog.csdn.net/harryhuang1990/article/details/33345447