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 .
Analysis: The difficulty of this problem is that the path can be any path and not limited to starting from the root. To solve this problem we can start with the decomposition problem and the classification discussion. For a binary tree, its maximum path either contains root or does not contain root, which is the key to solving the problem. If maximum path does not contain root, then this problem is decomposed into the maximum path sum of the left and right two subtrees, then the larger one. If maximum path contains root, we need to know that the maximum path sum containing the root->left in the left subtree is included in the maximum path sum (represented here in left_sum) and the right subtree contains root- >right maximum path sum (denoted by right_sum). We use Maxsum to represent the maximum path sum required by the topic, if Left_sum and right_sum are less than or equal to 0, then Maxsum = Max (maxsum, root->val); otherwise maxsum takes the current maxsum, Left_sum+root->val, Right_sum+root->val, maximum value of left_sum+root->val+right_sum. At this point, the problem can be solved. The code is as follows:
classSolution { Public: intMaxpathsum (TreeNode *root) { intMax_sum =int_min; MAX_PATH (Root, Max_sum); returnmax_sum; } intMax_path (TreeNode * root,int&max_sum) { if(Root = NULL)return 0; intL = MAX_PATH (root->Left , max_sum); intR = MAX_PATH (root->Right , max_sum); intsum = root->Val; if(L >0) Sum + =l; if(R >0) Sum + =R; Max_sum=Max (max_sum,sum); returnMax (L,R) >0? Max (L,r) + root->val:root->Val; }};
Leetcode:binary Tree Maximum Path Sum