The key to solving the problem is that this path can only go up first, reach a certain highest point, and then go down. In other words, there is only one turning opportunity. This tree recursively records the maximum value when a subnode is used as a turning point. It is worth noting that the value of the Tree node has a negative value, so if the sum of a sub-path is less than 0, discard it (set to 0 ).
Class solution {public: int maxpathsum (treenode * root) {int maxsum =-1 <30; int leftmax = pathmaxsum (root-> left, maxsum ); if (leftmax <0) leftmax = 0; int rightmax = pathmaxsum (root-> right, maxsum); If (rightmax <0) rightmax = 0; int pathsum = leftmax + rightmax + root-> val; If (pathsum> maxsum) return pathsum; elsereturn maxsum;} int pathmaxsum (treenode * node, Int & maxsum) {If (node = NULL) return 0; int Leftmax = pathmaxsum (node-> left, maxsum); If (leftmax <0) leftmax = 0; int rightmax = pathmaxsum (node-> right, maxsum ); if (rightmax <0) rightmax = 0; If (leftmax + rightmax + node-> Val> maxsum) // turn down at this pointmaxsum = leftmax + rightmax + node-> val; int pathmax = leftmax> rightmax? Leftmax: rightmax; pathmax + = node-> val; return pathmax ;}};
Leetcode-binary tree maximum path sum