[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 .

Hide TagsTree Depth-first Search

DFS, note the difference between the return value and the update max_sum,

Notice that when the last return returns, only the value in one Direction is returned, why? This is because in recursion, only the parent section
Point returned, there could be no path to l->root->r, only l->root or r->root.

However, the sum is computed by the path of the l->root->r.

In addition, the connectivity of the nodes is guaranteed by traversal, can traverse, then must be able to connect

/** Definition for binary tree * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * T Reenode (int x): Val (x), left (null), right (NULL) {} *}; */classSolution {intm_sum;  Public:        intDFS (TreeNode *root) {               if(Root = =NULL)return 0; intL = DFS (root->Left ); intR = DFS (root->Right ); intsum = root->Val; if(L >0) Sum+=l; if(R >0) Sum+=R;#if0cout<<"l\t"<< L <<Endl; cout<<"r\t"<< R <<Endl; cout<<"root\t"<< Root->val <<Endl; cout<<"sum\t"<< sum<<Endl;#endifM_sum=Max (m_sum, sum); if(Max (L, R) >0)                returnMax (L, R) + root->Val; Else                returnRoot->Val; }           intMaxpathsum (TreeNode *root) {M_sum=int_min;            DFS (root); returnm_sum; }};

[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.