Leetcode-binary tree maximum path sum

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.