Binary Tree Maximum Path Sum
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 .
The tree structure obviously uses the recursive return solution, the problem solving key:
1, for each level of recursion, only the value containing the root node of this layer can be returned to the upper level. Otherwise the path will not be contiguous.
2, the value returned is the root node plus a return value in the left and right subtree, and cannot be added with two return values. Otherwise the path will be forked.
In these two premises there is a need to pay attention to the problem, the top level returned value is not necessarily the maximum value to meet the requirements,
Because the path that corresponds to the maximum value does not necessarily contain the root value, it may exist on a subtree.
So the solution is to set the global variable maxsum, and constantly update the maximum value in the recursive process.
/** Definition for binary tree * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * T Reenode (int x): Val (x), left (null), right (NULL) {} *}; */classSolution { Public: intmaxsum; Solution () {Maxsum=int_min; } intMaxpathsum (TreeNode *root) {Helper (root); returnmaxsum; } intHelper (TreeNode *root) {//return the maxsum containing root//if the maxsum without root is the true answer, update the maxsum directly if(Root = =NULL)return 0; Else if(Root->left = = NULL && Root->right = =NULL) { //No Child, return the Root->val and maybe update the maxsumMaxsum = (maxsum >= root->val)? Maxsum:root->Val; returnRoot->Val; } Else if(Root->left! = NULL && Root->right = =NULL) { intleft = Helper (root->Left ); //return value must contain Root->val//if left <= 0, drop it intTMP = Root->val+max (0, left); Maxsum= (maxsum >= tmp)?maxsum:tmp; returntmp; } Else if(Root->left = = NULL && root->right! =NULL) { intright = Helper (root->Right ); //return value must contain Root->val//if right <= 0, drop it intTMP = Root->val+max (0, right); Maxsum= (maxsum >= tmp)?maxsum:tmp; returntmp; } Else { intleft = Helper (root->Left ); intright = Helper (root->Right ); //if left or right <= 0, drop it intTMP = Root->val+max (0, left) +max (0, right); Maxsum= (maxsum >= tmp)?maxsum:tmp; //attention here! return value contain at the most one child returnRoot->val+max (0, Max (left,right)); } }};
"Leetcode" Binary Tree Maximum Path Sum