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; }};