Recursion, DFS
The returned value is a pair <int, int>. First indicates the maximum pathsum of the two subtree that does not pass through the current root; second indicates the two subtree, use root-> left and root-> right as the maximum value of the path of the Start Node of the path.
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 pair<int,int> res = dfs(root);14 return res.first;15 }16 pair<int,int> dfs(TreeNode *root)17 {18 if(root == NULL)19 {20 return make_pair(0,0);21 }22 pair<int,int> left = dfs(root->left);23 pair<int,int> right = dfs(root->right);24 int leftCrossMax = left.first;25 int rightCrossMax = right.first;26 27 int leftMax = left.second > 0?left.second:0;28 int rightMax = right.second > 0?right.second:0;29 30 int maxNoCross = INT_MIN;31 if(root->left != NULL)32 {33 maxNoCross = max(maxNoCross,leftCrossMax);34 }35 if(root->right != NULL)36 {37 maxNoCross = max(maxNoCross,rightCrossMax);38 }39 int maxCross = leftMax+rightMax+root->val;40 int maxSum = max(maxCross,maxNoCross);41 42 int child = max(leftMax,rightMax);43 int maxChild = child > 0?child+root->val:root->val;44 return make_pair(maxSum,maxChild);45 }46 };
Leetcode -- Binary Tree maximum path sum