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