Binary Tree Maximum Path Sum

Source: Internet
Author: User

Binary Tree Maximum Path Sum
Question from LeetCode https://leetcode.com/problems/binary-tree-maximum-path-sum/
Binary Tree Maximum Path SumTotal Accepted: 37936 Total Submissions: 178064My SubmissionsQuestionSolution

 

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

 

Return6.

 

Show Tags Have you met this question in a real interview?
/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    int maxroute(TreeNode* root)    {        if(root==NULL)        return  0;        int left=maxroute(root->left);        int right=maxroute(root->right);        int tmp=left>right?left:right;       res=(root->val)>res?root->val:res;       if(tmp>left+right&&root->val+tmp>res)res=root->val+tmp;else if(root->val+left+right>res)             res=root->val+left+right;return (tmp>0?root->val+tmp:root->val);    }    int maxPathSum(TreeNode* root) {                if (root==NULL)         return 0;        if(root->left==NULL&&root->right==NULL)          return root->val;          res=root->val;          int cc= maxroute( root);        return res;    }     int res;};


Related Article

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.