面试题10:二叉树的最大路径和

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.

 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 maxVal = INT_MIN;
14         maxPathSum(root,maxVal);
15         return maxVal;
16     }
17     int maxPathSum(TreeNode *root,int& maxVal) {
18         if(root == nullptr) return 0;
19         int leftRes = max(0,maxPathSum(root->left,maxVal));
20         int rightRes = max(0,maxPathSum(root->right,maxVal));
21         maxVal = max(maxVal,leftRes + rightRes + root->val);
22         return max(leftRes,rightRes) + root->val;
23     }
24 };
原文地址:https://www.cnblogs.com/wxquare/p/6852317.html