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
Return6
.
/* ** 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 ;}};