【ATT】Binary Tree Maximum Path Sum
Q:
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
.
A: 树的问题,第一个考虑就是递归解决。
对于root为根节点的子树,maxPathSum的来源有以下几种情况
:1. root左子树
2. root右子树
3. 路径穿过root:分为三种情况:来自左子树+root;来自右子树+root;左子树+root+右子树。
int helper(TreeNode* root,int& cursum) 递归返回maxPathSum。其中cursum表示当前节点root作为路径end point时的maxsum。这是为了便于第3种情况的计算。
int maxPathSum(TreeNode *root) { // Start typing your C/C++ solution below // DO NOT write int main() function int cursum; return helper(root,cursum); } int helper(TreeNode* root,int& cursum) { if(!root) { cursum = 0; return INT_MIN; //注意循环结束条件:返回的是INT_MIN,而cursum = 0; } int lsum,rsum; int leftmax = helper(root->left,lsum); int rightmax = helper(root->right,rsum); cursum = max(root->val,max(lsum,rsum)+root->val); //注意这里有3种情况,别忘了root单一节点构成的路径 return max(max(leftmax,rightmax),max(cursum,lsum+rsum+root->val)); }