Given a binary tree, find the maximum path sum.
The path may start and end at any node in the tree.
The maximum path and note path to find the tree can start and end from any point.
I found that I am really good at the topic of trees, recursion is not difficult. Because there is a quantity to compare (Max and), you need to write a function again.
Since the path can start and end at any point, the left and right subtrees are less than or equal to 0 per recursion.
#include <iostream>#include<vector>#include<algorithm>#include<queue>#include<stack>using namespacestd;//Definition for binary treestructTreeNode {intVal; TreeNode*Left ; TreeNode*Right ; TreeNode (intx): Val (x), left (null), right (null) {}};classSolution { Public: intMaxpathsum (TreeNode *root) { if(Root = =NULL) { return 0; } intMaxpathsum = root->val;//the initial value of the assignment must be less than or equal to the lastmaxpathsumcur (root, Maxpathsum); returnmaxpathsum; } intMaxpathsumcur (TreeNode *root,int&maxpathsum) { if(Root = =NULL) { return 0; } intLsum = Maxpathsumcur (root->Left , maxpathsum); intRsum = Maxpathsumcur (root->Right , maxpathsum); intMaxpathsumcurrent = root->val;//The value of each root must be added to the left and right of the subtree increased to 0 if(Lsum >0) {maxpathsumcurrent+=lsum; } if(Rsum >0) {maxpathsumcurrent+=rsum; } maxpathsum=Max (maxpathsumcurrent, maxpathsum); returnMax (Root->val, Max (Root->val + lsum, root->val +rsum));//Returns the largest of the root nodes plus the left or right subtree or a separate root node. } voidCreate (TreeNode *&root) { intD; scanf ("%d", &d); if(d! =0) {root=NewTreeNode (d); Create (Root-Left ); Create (Root-Right ); } }};intMain () {solution S; TreeNode* T =NULL; S.create (T); intsum =s.maxpathsum (T); return 0;}
Leetcode Binary Tree Maximum Path Sum (medium)