Binary Tree Maximum Path Sum

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
Return 6.

Solution: Recursion...

 1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     int maxPathSum(TreeNode *root) {
13         int res = INT_MIN;
14         maxPathSumRe(root, res);
15         return res;
16     }
17     
18     int maxPathSumRe(TreeNode *root, int &res)
19     {
20         if(!root) return 0;
21         int l = maxPathSumRe(root->left, res);
22         int r = maxPathSumRe(root->right, res);
23         int sum = max(root->val, max(l,r) + root->val); // max (root as node)
24         res = max(sum, res);
25         res = max(root->val + l + r, res);
26         return sum;
27     }
28 };
原文地址:https://www.cnblogs.com/zhengjiankang/p/3665393.html