[LeetCode] 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.

参考资料:

  1. http://www.cnblogs.com/shawnhue/archive/2013/06/08/leetcode_124.html

  2. http://www.cnblogs.com/x1957/p/3275854.html

 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 ans;
13     int scanT(TreeNode* root){
14         if(root == NULL) return 0;
15         int left = scanT(root -> left);
16         int right = scanT(root -> right);
17         int val = root -> val;
18         if(left > 0) val += left;
19         if(right > 0) val += right;
20         if(val > ans) ans = val;
21         return max(root->val ,max(left +  root -> val , right + root -> val));
22     }
23     int maxPathSum(TreeNode *root) {
24         // Start typing your C/C++ solution below
25         // DO NOT write int main() function
26         if(root == NULL) return 0;
27         ans = root -> val;
28         scanT(root);
29         return ans;
30     }
31 };
原文地址:https://www.cnblogs.com/vincently/p/4231670.html