Binary Tree maximum path sum

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.

For example:
Given the below binary tree,

       1      /      2   3

 

Return6.

Idea: This question is to reach the maximum path and of another node starting from any node of the binary tree. It is a bit like finding the maximum continuous subsequence and, and this question is much more complicated than it is. Note that you cannot start from the root node. Otherwise, problems may occur. We should start recursive search from the bottom up to find the maximum path of the Left subtree and the value of the root node and the maximum path of the right subtree respectively, then, we can find the maximum path and value of the root node, root node, left subtree, root node, and right subtree.

/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    int getMaxSum(TreeNode *root,int &maxSum)    {        if(root==NULL)            return 0;        int left=getMaxSum(root->left,maxSum);        int right=getMaxSum(root->right,maxSum);        int CurSum=root->val;        if(left>0)            CurSum+=left;        if(right>0)            CurSum+=right;        maxSum=max(maxSum,CurSum);        return root->val+max(max(0,left),right);    }    int maxPathSum(TreeNode *root) {        if(root==NULL)            return 0;        int maxSum=INT_MIN;        getMaxSum(root,maxSum);        return maxSum;    }};

 

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.