# [Leetcode] Binary Tree maximum path sum (recursion)

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

` /*  ** Definition for binary tree * struct treenode {* int val; * treenode * left; * treenode * right; * treenode (int x): Val (x ), left (null), right (null ){}*};  */  Class  Solution { Public  :  Int Maxpathsum (treenode * Root ){  If (Root = Null)  Return   0  ;  Set < Int > S;  Return  Recursion (root, root, S );}  Private :  Int Recursion (treenode * P, treenode * root, Set < Int > & S ){  Int Left = 0 , Right = 0 , Parent = p-> Val;  Int Max = p-> Val;  If (P-> left = NULL & P-> right =Null)  Return  Max;  If (P-> Left) left = Recursion (p-> Left, root, S );  If (P-> Right) Right = Recursion (p-> Right, root, S );  If (Left> MAX & P-> Left) S. insert (left );  If (Right> MAX & P->Right) S. insert (right );  If (Left + parent> Max) max = Left + Parent;  If (Right + parent> Max) max = Right + Parent;  If (Right + Left + parent> Max) S. insert (Right + Left + Parent );  If (P = root &&! S. Empty ()){ Set < Int >:: Iterator iter = S. End (); ITER -- ;  Return (Max> (* ITER )? Max :(* ITER ));}  Return  Max ;}}; `

Related Keywords:

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.