124.Binary Tree Maximum Path Sum

Source: Internet
Author: User

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 .

  1. /** 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

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.