Given a binary tree, find the maximum path sum.
For this problem, a path was defined as any sequence of nodes from some starting node to any node in the tree along the par Ent-child connections. The path does not need to go through the root.
For example:
Given the below binary tree,
1 / 2 3
Return 6 .
Idea: This problem is also used in the bottom up way. Call the Help function recursively. If the incoming root node is empty, return 0 directly. Set Val to the maximum value of the current root node, recursively seek the sum of the paths of the left and right subtree, get the maximum path to the current node, and if the value is greater than result, update result. Finally returns the sum of the maximum paths through the current node, note that only one branch of the left and right subtree can be added, or there may be repeated addition .
/** Definition for a binary tree node. * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * TreeNode (int x): Val (x), left (null), right (NULL) {} *}; */classSolution {Private: intresult; Public: intHelp (TreeNode *root) { if(!root)return 0; intVal =root->Val; intLeft=help (root->Left ); intRight=help (root->Right ); if(left>0) Val+=Left ; if(right>0) Val+=Right ; Result=Max (result,val); returnMax (Root->val,max (root->val+left,root->val+Right )); } intMaxpathsum (treenode*root) { if(!root)return 0; Result=int_min; Help (Root); returnresult; }};
124.Binary Tree Maximum Path Sum