"Leetcode" Binary Tree Maximum Path Sum (medium)

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.

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)

Contact Us

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.