Leetcode:binary Tree Maximum Path Sum

Source: Internet
Author: User

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

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.